如何将此Ruby String转换为数组?

将以下Ruby String转换为数组的最佳方法是什么(我使用的是ruby 1.9.2 / Rails 3.0.11)

Rails控制台:

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

所需的输出:

 >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 

如果我这样做,例如:

 >Array(Choice.first.ingredients) 

我明白了:

 => ["[\"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\"]"] 

我敢肯定必须有一些明显的方法来解决这个问题。

为清楚起见,这将在表单中的textarea字段中进行编辑,因此应尽可能安全。

 class Item def ingredients_a ingredients.gsub(/(\[\"|\"\])/, '').split('", "') end end 
  1. 去除无关的角色
  2. 使用分离模式分割成数组元素

你有什么看起来像JSON,所以你可以这样做:

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

这避免了使用eval的许多恐怖。

虽然您应该首先考虑为什么要存储这样的数据,并考虑更改它,这样您就不必这样做了。 此外,您可能应该将其解析为ingredients的数组,以便该方法返回更有意义的内容。 如果您几乎总是对方法的返回值执行相同的操作,则该方法是错误的。

看起来, ingredients方法返回结果返回数组的.inspect输出。 这种输出不是很有用。 你有能力改变它以返回普通arrays吗?

不会做的是使用eval ,这只会增加已经hacky代码的hackiness。

就像Mark Thomas所说,修改你的成分方法,除非你真的想要两个分别返回字符串和数组的独立方法。 我假设你真的只想要返回一个数组。 为了论证,让我们说你的成分方法当前返回一个名为ingredients_string的变量。 像这样修改你的方法:

 def ingredients ... ingredients_array = ingredients_string.split('"') ingredients_array.delete_if { |element| %(", "[", "]").include? element } ingredients_array end 

不确定这是否起作用,但如果你想使用数组作为属性会发生什么,你可能要考虑序列化..

 class Item << ActiveWhatever serialize :ingredients, Array ... end 

有关序列化的更多信息,请访问http://api.rubyonrails.org/classes/ActiveRecord/Base.html

如果你的字符串数组是标准的JSON格式,只需使用JSON.parse()