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

后端 未结 7 1066
野的像风
野的像风 2020-12-12 18:47

I have an array:

int_array = [11,12]

I need to convert it into

str_array = [\'11\',\'12\']

I\'m new to t

7条回答
  •  盖世英雄少女心
    2020-12-12 19:37

    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)
    

提交回复
热议问题