我创建了一个Spam类型的新对象,attr_accessor既有hooray又有名字,我有初始化方法。我期待当我创建一个新对象时,该对象加载了一个带有“Whammy”的var变量和一个名为hooray的空数组。虽然我没有得到这种行为。谁能解释一下,谢谢你。
module Test
class Spam
attr_accessor :hooray, :name
def initialize
hooray = []
name = "Whammy"
end
end
end
Loading development environment (Rails 3.0.0)
irb(main):001:0> require 'Test'
=> nil
irb(main):002:0> test = Test::Spam.new
=> #<Test::Spam:0x000000031ff470>
irb(main):003:0> test.name
=> nil
irb(main):004:0> test.hooray
=> nil
irb(main):005:0> test.hooray << 5
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.<<
from (irb):5
from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands/console.rb:44:in `start'
from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands/console.rb:8:in `start'
from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
irb(main):006:0>
答案 0 :(得分:8)
这里的问题是你试图直接在initialize
方法中使用setter,但Ruby将其解释为创建局部变量,而不是调用self
上的setter。
def initialize
hooray = []
name = "Whammy"
end
您可以通过以下两种方式解决此问题;直接设置属性,例如@attribute
:
def initialize
@hooray = []
@name = "Whammy"
end
或者,如果你真的想要通过setter(例如,如果你有自定义setter做一些有趣的事情),请用self.setter
明确说明:
def initialize
self.hooray = []
self.name = "Whammy"
end
答案 1 :(得分:3)
您希望在类的实例中使用实例变量来定义属性,而不是局部变量。方法执行完毕后,局部变量将超出范围。下面的代码应该更符合您的需求:
module Test
class Spam
attr_accessor :hooray, :name
def initialize
@hooray = []
@name = "Whammy"
end
end
end