user9485690
user9485690

Reputation:

Ruby: String to Array

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

Upvotes: 0

Views: 259

Answers (2)

beniutek
beniutek

Reputation: 1767

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?

Upvotes: 1

Ursus
Ursus

Reputation: 30056

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.

Upvotes: 8

Related Questions