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
Share:
309,596

Related videos on Youtube

Sachin R
Author by

Sachin R

Fullstack Ninja/Lead: Ruby, Rails, JS, Angular, TDD/BDD, AWS Developer

Updated on February 09, 2022

Comments

  • Sachin R
    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ć
    Mladen Jablanović over 13 years
    Perhaps using "'#{i}'" instead.
  • oligan
    oligan over 12 years
    To quote Mladen, "Perhaps [use] "'#{i}'" instead."
  • djburdick
    djburdick over 12 years
    don't think map is needed. join should do the trick. see below
  • Bernard
    Bernard over 11 years
    That results in "12,34,35,231". It's missing the single quotes in the result.
  • corroded
    corroded over 11 years
    Okay added some string interpolation to add the first and last single quotes :P
  • Laf
    Laf over 11 years
    I think the OP needs to have the single quote as well.
  • Sean Cameron
    Sean Cameron almost 11 years
    This 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
    avihil almost 11 years
    Sean, you're wrong. Did you run the expression, at least once ??
  • Andrew Hodgkinson
    Andrew Hodgkinson almost 11 years
    It'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
    avihil over 10 years
    ['1','2','3'].map { |o| "\'#{o}\'" }.join(',')
  • zx1986
    zx1986 over 7 years
    how to revert this?
  • corroded
    corroded over 7 years
    what do you mean revert @zx1986
  • zx1986
    zx1986 over 7 years
    @corroded Sorry, I got it. JSON.parse("[12, 39, 100]") will return an array.
  • Claudio Floreani
    Claudio Floreani over 3 years
    This is the right way to do it, should be the accepted answer.