Convert array of integers to array of strings in Ruby?

I have an array:

int_array = [11,12] 

I need to convert it to

 str_array = ['11','12'] 

I'm new to this technology

+49
ruby
Apr 23 '09 at 9:57
source share
6 answers
 str_array = int_array.map(&:to_s) 
+100
Apr 23 '09 at 9:58
source share
 str_array = int_array.collect{|i| i.to_s} 
+43
Apr 23 '09 at 10:09
source share

display 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 get this with a single 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/167295/ )

 array = [1, 2, 3] array.map!(&:to_s) 
+15
Jul 09 '13 at 12:13
source share

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

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

+10
Apr 14 '16 at 9:08
source share

Run 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 elsewhere. Perhaps a confusion of the realm?

+4
Apr 23 '09 at 11:14
source share

Returns int

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

Returns a string

 y = 1,2,3,4,5 # => ["1", "2", "3", "4", "5"] 
-2
Feb 16 '11 at 8:40
source share



All Articles