'Ruby array to string conversion
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?
Solution 1:[1]
> a = ['12','34','35','231']
> a.map { |i| "'" + i.to_s + "'" }.join(",")
=> "'12','34','35','231'"
Solution 2:[2]
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 3:[3]
array.map{ |i| %Q('#{i}') }.join(',')
Solution 4:[4]
string_arr.map(&:inspect).join(',') # or other separator
Solution 5:[5]
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 6:[6]
> puts "'"+['12','34','35','231']*"','"+"'"
'12','34','35','231'
> puts ['12','34','35','231'].inspect[1...-1].gsub('"',"'")
'12', '34', '35', '231'
Solution 7:[7]
And yet another variation
a = ['12','34','35','231']
a.to_s.gsub(/\"/, '\'').gsub(/[\[\]]/, '')
Solution 8:[8]
irb(main)> varA
=> {0=>["12", "34", "35", "231"]}
irb(main)> varA = Hash[*ex.collect{|a,b| [a,b.join(",")]}.flatten]
...
Solution 9:[9]
irb(main):027:0> puts ['12','34','35','231'].inspect.to_s[1..-2].gsub('"', "'")
'12', '34', '35', '231'
=> nil
Solution 10:[10]
You can use some functional programming approach, transforming data:
['12','34','35','231'].map{|i| "'#{i}'"}.join(",")
Solution 11:[11]
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'"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
