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字段中进行编辑,因此应尽可能安全.
你有什么看起来像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以便该方法返回更有意义的内容.如果您几乎总是对方法的返回值执行相同的操作,则该方法是错误的.
class Item
def ingredients_a
ingredients.gsub(/(\[\"|\"\])/, '').split('", "')
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4529 次 |
| 最近记录: |