In Ruby, what is the most expressive way to map an array in such a way that certain elements are modified and the others left untouched?
This is a straight-forward way to do it:
old_a = ['a', 'b', 'c'] # ['a', 'b', 'c'] new_a = old_a.map { |x| (x=='b' ? x+'!' : x) } # ['a', 'b!', 'c']
Omitting the ‘leave-alone’ case of course if not enough:
new_a = old_a.map { |x| x+'!' if x=='b' } # [nil, 'b!', nil]
What I would like is something like this:
new_a = old_a.map_modifying_only_elements_where (Proc.new {|x| x == 'b'}) do |y| y + '!' end # ['a', 'b!', 'c']
Is there some nice way to do this in Ruby (or maybe Rails has some kind of convenience method that I haven’t found yet)?
Thanks everybody for replying. While you collectively convinced me that it’s best to just use map with the ternary operator, some of you posted very interesting answers!
I agree that the map statement is good as it is. It’s clear and simple,, and would easy for anyone to maintain.
If you want something more complex, how about this?