0

Ruby treats local variables differently inside def and inside define_method:

class MyClass
  y = 2
  def foo
    y ||= 0
    puts y
  end

  define_method :bar do
    y ||= 0
    puts y
  end
end

my_class = MyClass.new
my_class.foo # => 0
my_class.bar # => 2

I am wondering why.

sawa
  • 165,429
  • 45
  • 277
  • 381
user899119
  • 549
  • 1
  • 11
  • 25
  • 6
    It's because `def` creates new local variable scope, while the block passed to `define_method` call is a closure. – Marek Lipka Mar 19 '18 at 09:47
  • I've marked this as a duplicate. Not an exact one, but I think it answers your question. – Stefan Mar 19 '18 at 10:24

0 Answers0