itsKarma
itsKarma

Reputation: 57

ruby - reading string into array/subarray

I am looking for a good way to convert string like:

"[apples, oranges, [strawberries, peas, grapes]]"

into an array which will look like:

array = [apples, oranges, [strawberries, peas, grapes]].

therefore array[0] = ["apples"], array[1] = ["oranges"], and array[2] = ["strawberries", "peas", "grapes"]

So, whenever in my string I have another inner square brackets, the content between brackets will be a subarray of my base array.

Upvotes: 1

Views: 425

Answers (3)

DigitalRoss
DigitalRoss

Reputation: 146093

eval s.gsub /\w+/, '"\&"'

or, for an alternative result that might be useful...

eval s.gsub /\w+/, ':\&'

Now, these are vulnerable to code injection exploits if you are not in full control of the input, so you could install a JSON gem and do something like this:

require 'json'

JSON.parse s.gsub /\w+/, '"\&"'

Upvotes: 1

drexin
drexin

Reputation: 24423

Hm, if your strings would be surrounded by "" it would be easier, than you could just use a JSON parser ;-). But for this you would have to write your own parser. There are different parser generator gems for ruby. E.g.

Parslet: http://kschiess.github.com/parslet/

Treetop: http://treetop.rubyforge.org/

Upvotes: 1

Andrew Marshall
Andrew Marshall

Reputation: 96954

You can use gsub to wrap the words in quotes and then eval the string:

eval str.gsub(/\w+/) { |match| "'#{match}'" }

This assumes that your words are words in the sense of a regex: alphanumeric. Further, this is quick-and-dirty, and I don't recommend using eval if it can be avoided (by, for example, having your input be in a parseable serialization language) as it can be a security risk.

Upvotes: 1

Related Questions