将String转换为Array

时间:2014-04-15 07:40:59

标签: ruby-on-rails ruby ruby-on-rails-3.2

这是我的字符串:

 "[[question1, answer1],[queston2,ans2]]" 

如何转换为像

这样的数组
[[question1, answer1],[queston2,ans2]]

2 个答案:

答案 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"]]