Last Updated: February 25, 2016
·
514
· jrichardlai

Call a method on each object of a collection

def append_2s(word)
  word + "ss"
end

['test', 'ab', 'ss'].map(&method(:append_2s)) #=> ['testss', 'abss', 'ssss']

2 Responses
Add your response

Why don't use each?
['test', 'ab', 'ss'].each do {|a| append_2s(a) }

over 1 year ago ·

@emadb I think it is a little more elegant. But you can do it in even less chars with:

#removes whitespaces from items
['test ', ' ab', ' ss'].collect(&:strip)
over 1 year ago ·