Apply method to each element in array / enumerable

This is my array:

array = [:one,:two,:three] 

I want to apply the to_s method to all my array elements in order to get array = ['one','two','three'] .

How can I do this (converting each element of an enumerable to another)?

+34
arrays ruby enumerable
Jun 27 '11 at 17:58
source share
4 answers

This will work:

 array.map!(&:to_s) 
+57
Jun 27 '11 at 18:01
source share

It is worth noting that if you have an array of objects that you want to pass individually to a method with another caller, for example:

 # erb <% strings = %w{ cat dog mouse rabbit } %> <% strings.each do |string| %> <%= t string %> <% end %> 

To simplify, you can use the method method in combination with the behavior of the block extension:

 <%= strings.map(&method(:t)).join(' ') %> 

If you don't know what method does, it encapsulates the method associated with the character passed to it in Proc and returns it. Ampersand extends this Proc to a block that is pretty well passed to map . The return map is an array, and we probably want to format it a little nicer, hence join .

The caveat is that, as with Symbol#to_proc , you cannot pass arguments to the helper method.

+15
Jul 27 '11 at 15:51
source share

You can use map or map! accordingly, the first will return a new list, the second will change the list in place:

 >> array = [:one,:two,:three] => [:one, :two, :three] >> array.map{ |x| x.to_s } => ["one", "two", "three"] 
+14
Jun 27 '11 at 18:01
source share
  • array.map!(&:to_s) changes the source array to ['one','two','three']
  • array.map(&:to_s) returns an array ['one','two','three'] .
+7
Jun 27. 2018-11-18T00:
source share



All Articles