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

Nat*_*n W 5 ruby arrays string ruby-on-rails

将以下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
Run Code Online (Sandbox Code Playgroud)

所需的输出:

>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
Run Code Online (Sandbox Code Playgroud)

如果我这样做,例如:

>Array(Choice.first.ingredients)
Run Code Online (Sandbox Code Playgroud)

我明白了:

=> ["[\"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\"]"] 
Run Code Online (Sandbox Code Playgroud)

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

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

And*_*all 9

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

JSON.parse "[\"Bread, whole wheat, 100%, slice\", \"Egg Substitute\", \"new, Eggs, scrambled\"]"
#=> ["Bread, whole wheat, 100%, slice", "Egg Substitute", "new, Eggs, scrambled"]
Run Code Online (Sandbox Code Playgroud)

这避免了很多使用的恐怖eval.

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


Bry*_*Ash 5

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

  • +1这是问题的最直接*答案.一个*优雅*答案需要更多关于数组如何成为字符串的信息. (2认同)