如何将此Ruby字符串转换为数组? [英] How do I convert this Ruby String into an Array?
本文介绍了如何将此Ruby字符串转换为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将以下Ruby字符串转换为数组的最佳方法是什么(我使用的是ruby 1.9.2/Rails 3.0.11)
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控制台:
>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\"]"]
我肯定必须有一些明显的方法来解决这个问题.
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.
推荐答案
class Item
def ingredients_a
ingredients.gsub(/(\[\"|\"\])/, '').split('", "')
end
end
- 去除多余的字符
- 使用分隔模式将其拆分为数组元素
这篇关于如何将此Ruby字符串转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文