Tuesday, March 29, 2011

Two ways to simplify Array blocks in Ruby

1. If you have a block of the form { |v| v.mtd }:

ary.each { |v| v.mtd }          # normal way
ary.each(&:mtd)                 # simpler way

# Example:
ary = %w(abc def ghi jkl)
ary.each(&:upcase!)             # same as ary.each { |v| v.upcase! }

That works for other Array methods, like map. More on it.

2. If you have a block of the form { |v| mtd v }, and the method mtd does the same thing with all parameters:
ary.each { |v| mtd v }          # normal way
mtd *ary                        # simpler way

#Example:
ary = %w(abc def ghi jkl)
puts *ary                       # same as ary.each { |v| puts v }

See more on it.

No comments:

Post a Comment