StackedCrooked
StackedCrooked

Reputation: 35485

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 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?

Upvotes: 0

Views: 172

Answers (1)

mipadi
mipadi

Reputation: 410662

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

Upvotes: 3

Related Questions