質問

This is my String :

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

How can I convert into Array like

[[question1, answer1],[queston2,ans2]]
役に立ちましたか?

解決

You can do this easily by using 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]]

or

YAML.load(str)

他のヒント

With str = "[[question1, answer1],[queston2,ans2]]", it not possible to get output like

[[question1, answer1],[queston2,ans2]]. We can get output with string elements like [["question1", "answer1"], ["queston2", "ans2"]] by doing just require 'yaml' and YAML.load str.

And if you have identifiers question1, answer1, queston2 and ans2 then you can just get an array of corresponding values for these identifiers by using eval str.

Considering:--

question1 = "Which language is the best language?"
answer1 = "Ruby"
queston2 = "Which framework is the best framework?"
ans2 = "Rails 4.1"

We will get an array like following:--

eval str
=> [["Which language is the best language?", "Ruby"], 
     ["Which framework is the best framework?", "Rails 4.1"]]
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top