Home > Mobile >  How to convert array to string array?
How to convert array to string array?

Time:09-16

Here i have ruby code like this for converting arrays to string array and also observed that difference between puts and print/p both or giving different output

a= ["ruby"]
print a.to_s

output:

"[\"ruby\"]"

But need like this when i use print/p and class should be string

"["ruby"]"  or '["ruby"]'

CodePudding user response:

Try this

"'#{['ruby','othersElements'].join("', '")}'"

Where "," is the element separator

.join("', '")

CodePudding user response:

You just need to_s. Its output is compatible with eval (as long as elements can be serialized with to_s themselves):

string = ["a", "b", "c"].to_s
=> "[\"a\", \"b\", \"c\"]"

rebuilt = eval string
=> ["a", "b", "c"]

rebuilt.class
=> Array

rebuilt[0].class
=> String

CodePudding user response:

If you accept having single quotes instead of double quotes:

array = ['ruby', 'is', 'cool']

"['#{array.join("', '")}']"
# => "['ruby', 'is', 'cool']"


# You can then define you own method:
def puts_array(array)
  puts "['#{array.join("', '")}']"
end

# Or overwrite Array#to_s method
class Array
  def to_s
    "['#{self.join("', '")}']"
  end
end

puts_array(array)
# => "['ruby', 'is', 'cool']"
puts array.to_s
# => "['ruby', 'is', 'cool']"
  •  Tags:  
  • ruby
  • Related