Ruby Proc object as public member variable doesn't work?
I am a bit of a Ruby noob when it comes to the more advanced features. Currently I am experiencing with Proc objects. Can someone tell 开发者_Go百科me what is wrong with this code sample?
class Tester
@printer = Proc.new do |text|
puts text
end
attr_accessor :printer
end
t = Tester.new
t.printer.call("Hello!")
It gives me the following error:
Test.rb:10: undefined method `call' for nil:NilClass (NoMethodError)
I don't immediately see why it shouldn't work. Can someone enlighten me?
You're not setting @printer
in the class's initialize
method. This'll work:
class Tester
def initialize
@printer = Proc.new { |t| puts t }
end
attr_accessor :printer
end
精彩评论