0

How would you convert a string to an array in Ruby?

What I want to do is convert a string like "[value1, value2, value3]" to an array [value1, value2, value3]. Keep in mind some of these values may be strings themselves.

I am trying to write it in a method called str_to_ary.

def str_to_ary
  @to_convert = self
  #however everything I try beyond this point fails
end
2
  • 3
    Could you use some example values instead of value1, value2, value3? As is the question looks a bit ambiguous. It can be easily interpreted that they can be local variables defined beforehand, in which case this will require some eval black magic. Commented Mar 8, 2019 at 15:45
  • 1
    You wish to convert a string to an array containing value1, value2 and value3. Presumably those are local variables or methods (not literals). Is that what you intend? Commented Mar 8, 2019 at 21:52

2 Answers 2

8

Well, that looks like a JSON.

require 'json'

def str_to_ary
  JSON.parse(@to_convert)
end

Note that this is true and works only if those string values in there are between double quotes, not single quotes.

Sign up to request clarification or add additional context in comments.

8 Comments

That worked just as intended. I appreciate the help. :)
Great, glad to hear that :)
Don't forget to mark as accepted answers that solved your problem. This helps others find solutions that work.
The string the OP posted is not valid JSON. An array must contain an array, an object, a number, a string, or other primitive type. value1 is neither of those things, therefore the string is not valid JSON and cannot be parsed as JSON.
@JörgWMittag those value1 etc are numbers or strings
|
1

well if you know that [ is always on the first place and ] is always on the last place then you can start with

string = "[X, 1, Test, 22, 3]"
trimmed = string[1,string.length-2]
array = trimmed.split(", ")

array => ["X", " 1", " Test", " 22", " 3"]

if you want to then cast 1, 22 or 3 into Integers then that's a different problem that requires more thought. What values are you expecting to have in the array?

3 Comments

split on ", " to get rid of the spaces
Simple parsers like this inevitably end up with tons of corner cases (missing values, mangled values, crashes). Best to stick with a standard parser like json if you know the format fits
Based on the OP's example, "[X, 1, Test, 22, 3]" is to be converted to [X, 1, Test, 22, 3], not an array of strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.