Ruby headscratcher - instance variable isn't outputted
-
03-07-2019 - |
Question
I'm probably doing something stupid but I can't figure out what it is.
The output I'm seeing from this program is
foo
test
What I'm expecting to see is
foo
abc
test
Does anyone see anything obviously wrong here?
class Foo
def initialize(l)
@label = l
end
def label
@label
end
def abc
@abc
end
def abc=(abc)
@abc
end
end
foo = Foo.new("foo")
foo.abc=("abc")
puts foo.label
puts foo.abc
puts "test"
Solution
You never set @abc in your abc=
method. It should look like
def abc=(val)
@abc = val
end
OTHER TIPS
In addition to Logan's answer which tells you what the error was, here's how that error never would have occurred in the first place:
class Foo
def initialize(l)
@label = l
end
attr_reader :label
attr_accessor :abc
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow