문제

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