这是我的字符串:
"[[question1, answer1],[queston2,ans2]]"
如何转换为像
这样的数组[[question1, answer1],[queston2,ans2]]
答案 0 :(得分:3)
您可以使用yaml
require 'yaml'
str = "[[question1, answer1],[queston2,ans2]]"
# transform your string in a valid YAML-String
str.gsub!(/(\,)(\S)/, "\\1 \\2")
YAML::load(str)
# => [[question1, answer1],[queston2,ans2]]
或
YAML.load(str)
答案 1 :(得分:2)
使用str = "[[question1, answer1],[queston2,ans2]]"
,无法获得
[[question1, answer1],[queston2,ans2]]
。我们只需[["question1", "answer1"], ["queston2", "ans2"]]
和require 'yaml'
即可获得YAML.load str
等字符串元素的输出。
如果您有标识符question1, answer1, queston2 and ans2
,那么您可以使用eval str
获取这些标识符的相应值数组。
考虑到: -
question1 = "Which language is the best language?"
answer1 = "Ruby"
queston2 = "Which framework is the best framework?"
ans2 = "Rails 4.1"
我们将获得如下数组: -
eval str
=> [["Which language is the best language?", "Ruby"],
["Which framework is the best framework?", "Rails 4.1"]]