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


Jan 02 2011

Learn a bit of Ruby every day: Dir.exist?

Category: ruby,tutorialgiordano scalzo @ 10:38 pm

Introduced in 1.9, it’s a cool method to know if a directory exists:

Dir.exist?("/tmp") # => true
Dir.exist?("/temp") # => false

A more correct alias is Dir.exist?.


Jan 01 2011

Learn a bit of Ruby every day: Enumeration.reduce

Category: me,rubygiordano scalzo @ 11:30 pm

Ilya Grigorik is an awesome programmer who recently launched the geek equivalent of Farmville: VimGolf, the idea that every geek had, but nobody created.

From today he starts to tweet a piece of Ruby every day, mainly 1.9.2.

The first tweet is about Enumeration.reduce, an alternative, and more speaking, name for Enumeration.inject:
ruby-1.9.2-p136 > (1..3).reduce(:+)
=> 6

The strange argument is the symbol for plus, the operation to do to each element.
A more verbose, and less magic, version is:
ruby-1.9.2-p136 > (1..3).reduce {|sum, e| sum+e}
=> 6