Jan 05 2011

Learn a bit of Ruby every day: block local variable

Category: ruby,tutorialgiordano scalzo @ 5:52 pm

In Ruby 1.8.7 it wasn’t possible define a local variable to a block, so the following code produces an exception:

class Shape
  def initialize(args)
    @sides = args[:sides]
  end
  def draw
    puts "Drawing #{@sides} sides"
  end
end

square = Shape.new(sides: 4)
sum = 0
(1..3).each do |value|
  square = value * value
  sum	+= square
end
puts sum
square.draw

Ruby 1.9.2 it’s possible add a local variable to a block:

class Shape
  def initialize(args)
    @sides = args[:sides]
  end
  def draw
    puts "Drawing #{@sides} sides"
  end
end

square = Shape.new(sides: 4)
sum = 0
(1..3).each do |value; square|
  square = value * value
  sum	+= square
end
puts sum
square.draw

Now it works as expected