Ruby array to string conversion
RubyArraysStringRuby Problem Overview
I have a ruby array like ['12','34','35','231']
.
I want to convert it to a string like '12','34','35','231'
.
How can I do that?
Ruby Solutions
Solution 1 - Ruby
I'll join the fun with:
['12','34','35','231'].join(', ')
# => 12, 34, 35, 231
EDIT:
"'#{['12','34','35','231'].join("', '")}'"
# => '12','34','35','231'
Some string interpolation to add the first and last single quote :P
Solution 2 - Ruby
> a = ['12','34','35','231']
> a.map { |i| "'" + i.to_s + "'" }.join(",")
=> "'12','34','35','231'"
Solution 3 - Ruby
try this code ['12','34','35','231']*","
will give you result "12,34,35,231"
I hope this is the result you, let me know
Solution 4 - Ruby
array.map{ |i| %Q('#{i}') }.join(',')
Solution 5 - Ruby
string_arr.map(&:inspect).join(',') # or other separator
Solution 6 - Ruby
I find this way readable and rubyish:
add_quotes =- > x{"'#{x}'"}
p ['12','34','35','231'].map(&add_quotes).join(',') => "'12','34','35','231'"
Solution 7 - Ruby
> puts "'"+['12','34','35','231']*"','"+"'"
'12','34','35','231'
> puts ['12','34','35','231'].inspect[1...-1].gsub('"',"'")
'12', '34', '35', '231'
Solution 8 - Ruby
And yet another variation
a = ['12','34','35','231']
a.to_s.gsub(/\"/, '\'').gsub(/[\[\]]/, '')
Solution 9 - Ruby
irb(main)> varA
=> {0=>["12", "34", "35", "231"]}
irb(main)> varA = Hash[*ex.collect{|a,b| [a,b.join(",")]}.flatten]
...
Solution 10 - Ruby
irb(main):027:0> puts ['12','34','35','231'].inspect.to_s[1..-2].gsub('"', "'")
'12', '34', '35', '231'
=> nil
Solution 11 - Ruby
You can use some functional programming approach, transforming data:
['12','34','35','231'].map{|i| "'#{i}'"}.join(",")
Solution 12 - Ruby
suppose your array :
arr=["1","2","3","4"]
Method to convert array to string:
Array_name.join(",")
Example:
arr.join(",")
Result:
"'1','2','3','4'"
Solution 13 - Ruby
array.inspect.inspect.gsub(/\[|\]/, "")
could do the trick