Transforming a set
I have a set of strings that I want to universal开发者_如何学Goly transform by running through a function, for example, add_underscore(string)
.
Is there a native syntactic way to do this without iteration code?
You can use map for applying a function to each element in a collection.
>> a = [ "a", "b", "c", "d" ]
=> ["a", "b", "c", "d"]
>> a.map { |x| x.upcase }
=> ["A", "B", "C", "D"]
Building on The MYYN's answer…
set = [ 'one', 'two', 'three', 'four' ]
# in Ruby 1.9 this:
set.map &:capitalize # => [ 'One', 'Two', 'Three', 'Four' ]
# is the same as this:
set.map { |x| x.capitalize }
Note that map
returns a new array, it doesn't modify the existing one. Also, it uses enumerable
to iterate over each item in the array; it's still the best way to do this, just thought you might care to know.
精彩评论