开发者

Ruby Proc object as public member variable doesn't work?

开发者 https://www.devze.com 2022-12-11 01:26 出处:网络
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?

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
0

精彩评论

暂无评论...
验证码 换一张
取 消