Vladimir Tsukanov
Vladimir Tsukanov

Reputation: 4459

Apply method to each elements in array/enumerable

This is my array:

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

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

How can I do this (converting each element of the enumerable to something else)?

Upvotes: 54

Views: 50816

Answers (4)

sawa
sawa

Reputation: 168081

This will work:

array.map!(&:to_s)

Upvotes: 88

coreyward
coreyward

Reputation: 80041

It's worth noting that if you have an array of objects you want to pass individually into a method with a different caller, like this:

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

You can use the method method combined with block expansion behavior to simplify:

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

If you're not familiar, what method does is encapsulates the method associated with the symbol passed to it in a Proc and returns it. The ampersand expands this Proc into a block, which gets passed to map quite nicely. The return of map is an array, and we probably want to format it a little more nicely, hence the join.

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

Upvotes: 17

Arun Kumar Arjunan
Arun Kumar Arjunan

Reputation: 6857

  • array.map!(&:to_s) modifies the original array to ['one','two','three']
  • array.map(&:to_s) returns the array ['one','two','three'].

Upvotes: 10

miku
miku

Reputation: 188004

You can use map or map! respectively, the first will return a new list, the second will modify the list in-place:

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

>> array.map{ |x| x.to_s }
=> ["one", "two", "three"]

Upvotes: 20

Related Questions