46

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)?

lulalala
  • 16,796
  • 13
  • 106
  • 167
Vladimir Tsukanov
  • 3,869
  • 7
  • 27
  • 33
  • Possible duplicate of [Convert an array of integers into an array of strings in Ruby?](http://stackoverflow.com/questions/781054/convert-an-array-of-integers-into-an-array-of-strings-in-ruby) – Nakilon Oct 03 '15 at 17:49

4 Answers4

79

This will work:

array.map!(&:to_s)
sawa
  • 160,959
  • 41
  • 265
  • 366
19

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"]
miku
  • 172,072
  • 46
  • 300
  • 307
17

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.

coreyward
  • 73,396
  • 19
  • 130
  • 155
8
  • array.map!(&:to_s) modifies the original array to ['one','two','three']
  • array.map(&:to_s) returns the array ['one','two','three'].
Arun Kumar Arjunan
  • 6,687
  • 30
  • 35
  • @sawa: Actually, that's not true. Ruby-On-Rails is actually a programming language, with more questions asked about it than about Ruby. But just like Perl, CLU and SmallTalk, Ruby has incorporated the best bits of it into its language. ;) http://xkcd.com/386/ – Andrew Grimm Jun 27 '11 at 23:23
  • @Andrew Okay. Thanks. I removed my comment right before you gave some. – sawa Jun 27 '11 at 23:26
  • For those wondering what I was humorously replying to, @sawa basically asked if the answerer knew that Ruby is a language, and that Rails is a framework that runs on Ruby, because @sawa thought that Symbol#to_proc was Rails-only in 1.8.7. – Andrew Grimm Jun 27 '11 at 23:38