Aydar Omurbekov
Aydar Omurbekov

Reputation: 2107

variable that defined within a block

when Ruby executes the line puts "#{number}...",
why it can’t know that the number there is supposed to be a variable?
It is trying to execute self.number method

class Roulette
  def method_missing(name, *args)
    person = name.to_s.capitalize
    3.times do
      number = rand(10) + 1
      puts "#{number}..."
    end
    "#{person} got a #{number}"
  end
end

number_of = Roulette.new
puts number_of.bob

Upvotes: 1

Views: 88

Answers (1)

Agis
Agis

Reputation: 33626

Blocks in Ruby introduce a new lexical scope.

Therefore variables declared inside a block are local to the block's scope and cannot be accessed outside of it.

So the number variable only lives inside the block 3.times do ... end.

As to what happens when your code executes:

When execution reaches the line "#{person} got a #{number}" Ruby will see that number does not exist as a local variable and then will try to call a method with that name. It will not find a method either so then it will execute the method_missing you defined.

Therefore you have kind-of a recursive function that will call itself indefinitely, so it will cause a SystemStackError exception.

Upvotes: 3

Related Questions