24

I send an array from rest client and received it like this: "[1,2,3,4,5]"

Now I just want to convert it into Array without using Ruby's eval method. Any Ruby's default method that we could use for this?

 "[1,2,3,4,5]" => [1,2,3,4,5]
4
  • Does the API use a specific format like JSON or YAML? Commented Jan 26, 2016 at 7:51
  • ...because if not, consider adopting one, you need a serialization format anyway. Commented Jan 26, 2016 at 8:18
  • 1
    API uses JOSN format Commented Jan 26, 2016 at 8:26
  • 3
    @GhulamJilani you should strongly consider using Ruby's JSON library as shown in Cary Swoveland's answer below. Commented Jan 26, 2016 at 9:08

3 Answers 3

67
require 'json'

JSON.parse "[1,2,3,4,5]"
  #=> [1, 2, 3, 4, 5] 

JSON.parse "[[1,2],3,4]"
  #=> [[1, 2], 3, 4] 
Sign up to request clarification or add additional context in comments.

2 Comments

this one should be the accepted answer considering its votes
@M.Habib agreed it covers any scenario from "[1,2,3]" to '["it covers", "any,scenario",["this","too"]]'
8

Perhaps this?

   s.tr('[]', '').split(',').map(&:to_i)

4 Comments

Caution: This approach effectively flattens multidimensional arrays.
With using '["12", "45"]'.tr('[]','').map(&:to_i) it return error : undefined method map
tbh, at this point, you should just use JSON.parse lol. But if you reallyyyyy wanted, '["12", "45"]'.tr('["]','').split(',')
2nd caution: If you want it to raise an ArgumentError for non-integers like '2.2' or bad data like '2sdf' then replace the .map(&:to_i) at the end with .map { |x| Integer(x) }. (Or .map { |x| Float(x) } if you want floats).
5

If you want to avoid eval, yet another way:

"[1,2,3,4,5]".scan(/\d+/).map(&:to_i) #assuming you have integer Array as String
#=> [1, 2, 3, 4, 5]

3 Comments

Using this '[88,89,100]'.scan(/\d/) returns ["8", "8", "8", "9", "1", "0", "0"]
@VishwasNahar tweaking pattern to \d+ will solve this. I have updated my answer. Thanks
PS: you should definitely use JSON.parse @VishwasNahar

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.