Vivek Bhusani
Vivek Bhusani

Reputation: 11

How to add double quotes to elements inside a array in Ruby

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?

Upvotes: 0

Views: 291

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110755

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.

Upvotes: 1

steenslag
steenslag

Reputation: 80095

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.

Upvotes: 1

Related Questions