Showing posts with label array. Show all posts
Showing posts with label array. Show all posts
Tuesday, March 29, 2011
Two ways to simplify Array blocks in Ruby
1. If you have a block of the form
That works for other Array methods, like
2. If you have a block of the form
See more on it.
{ |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.
Subscribe to:
Posts (Atom)
