tags:

views:

46

answers:

1

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?

+3  A: 

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
mipadi
Further info: The @printer variable defined in StackedCrooked's code belongs to the Tester class itself. Outside of instance methods, all code in a class definition uses the class as `self` — so if you set an instance variable, you're setting an instance variable of the class (which is an instance of Class) rather than an instance variable of any particular instance.
Chuck