1

This is my String :

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

How can I convert into Array like

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

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

There is no need of doing gsub here, as you would get an array with string elements only. YAML.load(str) is enough here.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.