66

I have an array:

int_array = [11,12]

I need to convert it into

str_array = ['11','12']

I'm new to this technology

Mike Woodhouse
  • 51,832
  • 12
  • 88
  • 127
  • possible duplicate of [Apply method to array elements](http://stackoverflow.com/questions/6496931/apply-method-to-array-elements) – Andrew Grimm Dec 12 '11 at 21:59

7 Answers7

134
str_array = int_array.map(&:to_s)
gtd
  • 16,956
  • 6
  • 49
  • 65
46
str_array = int_array.collect{|i| i.to_s}
nuriaion
  • 2,621
  • 2
  • 23
  • 18
  • This didn't work for me until I remembered that to do it in place in the array you have to call collect! instead of collect. Then it worked fine. – Garth Aug 09 '12 at 00:19
  • 7
    shorter to write it this way: `str_array = int_array.map(&:to_s)` the _"&:"_ means call the "to_s" method on every element of the array. and "map" is a shorter synonym for "collect" – Rob Dec 06 '12 at 21:03
23

array.map(&:to_s) => array of integers into an array of strings

array.map(&:to_i) => array of strings into an array of integers

Rahul Patel
  • 1,386
  • 1
  • 14
  • 16
17

map and collect functions will work the same here.

int_array = [1, 2, 3]

str_array = int_array.map { |i| i.to_s }
=> str_array = ['1', '2', '3']

You can acheive this with one line:

array = [1, 2, 3]
array.map! { |i| i.to_s }

and you can use a really cool shortcut for proc: (https://stackoverflow.com/a/1961118/2257912)

array = [1, 2, 3]
array.map!(&:to_s)
Community
  • 1
  • 1
Idan Wender
  • 977
  • 8
  • 10
4

Start up irb

irb(main):001:0> int_array = [11,12]
=> [11, 12]
irb(main):002:0> str_array = int_array.collect{|i| i.to_s}
=> ["11", "12"]

Your problem is probably somewhere else. Perhaps a scope confusion?

srboisvert
  • 12,679
  • 15
  • 63
  • 87
0

the shortest option:

int_array.map!(&:to_s)
-3

Returns Int

x = [1,2,3,4,5,6,7,8,9,10] # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Returns String

y = 1,2,3,4,5 # => ["1", "2", "3", "4", "5"]
ChuckJHardy
  • 6,956
  • 6
  • 35
  • 39