Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert this Ruby String into an Array?

What is the best way to turn the following Ruby String into an Array (I'm using ruby 1.9.2/Rails 3.0.11)

Rails console:

>Item.first.ingredients
=> "[\"Bread, whole wheat, 100%, slice\", \"Egg Substitute\", \"new, Eggs, scrambled\"]"
>Item.first.ingredients.class.name
=> "String"
>Item.first.ingredients.length
77

The desired output:

>Item.first.ingredients_a
["Bread, whole wheat, 100%, slice", "Egg Substitute", "new, Eggs, scrambled"]
>Item.first.ingredients_a.class.name
=> "Array
>Item.first.ingredients_a.length
=> 3

If I do this, for instance:

>Array(Choice.first.ingredients)

I get this:

=> ["[\"Bread, whole wheat, 100%, slice\", \"Egg Substitute\", \"new, Eggs, scrambled\", \"Oats, rolled, old fashioned\", \"Syrup, pancake\", \"Water, tap\", \"Oil, olive blend\", \"Spice, cinnamon, ground\", \"Seeds, sunflower, kernels, dried\", \"Flavor, vanilla extract\", \"Honey, strained/extracted\", \"Raisins, seedless\", \"Cranberries, dried, swtnd\", \"Spice, ginger, ground\", \"Flour, whole wheat\"]"] 

I'm sure there must be some obvious way to solve this.

For clarity, this will be editable in a textarea field in a form, so should be made as secure as possible.

like image 398
Nathan W Avatar asked May 10 '12 01:05

Nathan W


1 Answers

What you have looks like JSON, so you can do:

JSON.parse "[\"Bread, whole wheat, 100%, slice\", \"Egg Substitute\", \"new, Eggs, scrambled\"]"
#=> ["Bread, whole wheat, 100%, slice", "Egg Substitute", "new, Eggs, scrambled"]

this avoids a lot of the horrors of using eval.

Though you should really think about why you're storing your data like that in the first place, and consider changing it so you don't have to do this. Further, it's likely that you should be parsing it to an array in ingredients so that the method returns something more meaningful. If you're almost always doing the same operation on a method's return value, the method is wrong.

like image 85
Andrew Marshall Avatar answered Oct 29 '22 04:10

Andrew Marshall