Ruby 无法从方法访问数组
我有密码:Ruby 无法从方法访问数组,ruby,instance-variables,Ruby,Instance Variables,我有密码: class Blah @hello = ["a", "b", "c"] puts @hello[0] def something() puts "abc" #puts @hello[0] end end z = Blah.new() z.something() puts @hello[0] 其结果是输出: a abc 如果我取消注释 #puts @hello[0] 并尝试输出数组的第一个结果@hello,即a,我得到以下错误: array_
class Blah
@hello = ["a", "b", "c"]
puts @hello[0]
def something()
puts "abc"
#puts @hello[0]
end
end
z = Blah.new()
z.something()
puts @hello[0]
其结果是输出:
a
abc
如果我取消注释
#puts @hello[0]
并尝试输出数组的第一个结果@hello
,即a
,我得到以下错误:
array_2.rb:13:in `something': undefined method `[]' for nil:NilClass (NoMethodError)
为什么我不能得到结果:
a
abc
a
为什么我的代码不起作用?像
@example
这样的数组不仅可以在类中访问,还可以在something
方法中访问。为什么我不能在方法中访问@hello[0]
?为什么@hello[0]
只能在类中访问,而不能在方法中访问?需要有人修复我的代码,以便我可以在方法中访问@array
。您需要在实例方法中初始化实例变量,但您是在类主体的范围内执行此操作,这是行不通的
如果从初始化
方法设置@hello
,则其工作方式应与预期相同
class Blah
def initialize
@hello = ["a","b","c"]
end
def something()
puts @hello[0]
end
end
Blah.new.something #=> 'a'
它以这种方式工作,因此在实例化类时可以传递参数,每个实例的实例变量中可能存储了不同的数据。第一个
@hello
是类实例变量,而不是实例变量。