Ruby headscratcher - 不输出实例变量
-
03-07-2019 - |
题
我可能做了一些愚蠢的事情,但我无法弄清楚它是什么。
我从这个程序看到的输出是
foo
test
我期待看到的是
foo
abc
test
有人在这里看到任何明显错误吗?
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"
解决方案
您永远不会在 abc =
方法中设置@abc。它应该看起来像
def abc=(val)
@abc = val
end
其他提示
除了Logan的答案,它告诉你错误是什么,这里的错误永远不会发生在第一位:
class Foo
def initialize(l)
@label = l
end
attr_reader :label
attr_accessor :abc
end
不隶属于 StackOverflow