Convert an array of integers into an array of strings in Ruby?

Ruby

Ruby Problem Overview


I have an array:

int_array = [11,12]

I need to convert it into

str_array = ['11','12']

I'm new to this technology

Ruby Solutions


Solution 1 - Ruby

str_array = int_array.map(&:to_s)

Solution 2 - Ruby

str_array = int_array.collect{|i| i.to_s}

Solution 3 - Ruby

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

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

Solution 4 - Ruby

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)

Solution 5 - Ruby

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?

Solution 6 - Ruby

the shortest option:

int_array.map!(&:to_s)

Solution 7 - Ruby

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"]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionswathiView Question on Stackoverflow
Solution 1 - RubygtdView Answer on Stackoverflow
Solution 2 - RubynuriaionView Answer on Stackoverflow
Solution 3 - RubyRahul PatelView Answer on Stackoverflow
Solution 4 - RubyIdan WenderView Answer on Stackoverflow
Solution 5 - RubysrboisvertView Answer on Stackoverflow
Solution 6 - RubyАндрей МосинView Answer on Stackoverflow
Solution 7 - RubyChuckJHardyView Answer on Stackoverflow