Ruby array to string conversion
309,596
Solution 1
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
> a = ['12','34','35','231']
> a.map { |i| "'" + i.to_s + "'" }.join(",")
=> "'12','34','35','231'"
Solution 3
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
array.map{ |i| %Q('#{i}') }.join(',')
Solution 5
string_arr.map(&:inspect).join(',') # or other separator
Related videos on Youtube
Author by
Sachin R
Fullstack Ninja/Lead: Ruby, Rails, JS, Angular, TDD/BDD, AWS Developer
Updated on February 09, 2022Comments
-
Sachin R over 2 years
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?
-
Mladen Jablanović over 13 yearsPerhaps using
"'#{i}'"
instead. -
oligan over 12 yearsTo quote Mladen, "Perhaps [use]
"'#{i}'"
instead." -
djburdick over 12 yearsdon't think map is needed. join should do the trick. see below
-
Bernard over 11 yearsThat results in "12,34,35,231". It's missing the single quotes in the result.
-
corroded over 11 yearsOkay added some string interpolation to add the first and last single quotes :P
-
Laf over 11 yearsI think the OP needs to have the single quote as well.
-
Sean Cameron almost 11 yearsThis does not produce the correct output - the values needs to be wrapped in single quotes. If this was the desired output then string_arr.join(",") would be the better option.
-
avihil almost 11 yearsSean, you're wrong. Did you run the expression, at least once ??
-
Andrew Hodgkinson almost 11 yearsIt's still wrong. It results in double quotes around the array entries, not single quotes. Plus it relies upon an assumption about the format that "inspect()" prints data, which makes it fragile.
-
avihil over 10 years['1','2','3'].map { |o| "\'#{o}\'" }.join(',')
-
zx1986 over 7 yearshow to revert this?
-
corroded over 7 yearswhat do you mean revert @zx1986
-
zx1986 over 7 years@corroded Sorry, I got it.
JSON.parse("[12, 39, 100]")
will return an array. -
Claudio Floreani over 3 yearsThis is the right way to do it, should be the accepted answer.