Home > Mobile >  How to add double quotes to elements inside a array in Ruby
How to add double quotes to elements inside a array in Ruby

Time:04-20

I am very new to the Ruby, I have array and I want to add double quotes to all alpha-numeric elements

array I have: a = [a255b78, wr356672]

Array i required: a =["a255b78", "wr356672"]

Is there any direct way to do this?

CodePudding user response:

Get rid of the "[]" and split on ", ":

str = "[a255b78, wr356672]"
p arr = str[1..-2].split(", ") # => ["a255b78", "wr356672"]

This does NOT add double quotes to all alpha-numeric elements; it converts a String to an Array of Strings.

CodePudding user response:

str = "[a255b78, wr356672]"
str.scan(/\w /)
  #=> ["a255b78", "wr356672"]

See String#scan. The regular expression matches one or more word characters. Word characters (matching \w) are letters, digits and the underscore.

  • Related