By Ghulam Jilani


2016-01-26 07:42:52 8 Comments

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]

3 comments

@Cary Swoveland 2016-01-26 08:08:23

require 'json'

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

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

@shivam 2016-01-26 07:51:57

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]

@Ho Man 2016-01-26 07:47:57

Perhaps this?

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

@Terra Ashley 2016-06-09 04:53:07

Caution: This approach effectively flattens multidimensional arrays.

Related Questions

Sponsored Content

23 Answered Questions

[SOLVED] Check if a value exists in an array in Ruby

  • 2009-12-31 17:49:03
  • user211662
  • 716021 View
  • 1160 Score
  • 23 Answer
  • Tags:   ruby arrays

26 Answered Questions

[SOLVED] How can I rename a database column in a Ruby on Rails migration?

17 Answered Questions

[SOLVED] How do I remove blank elements from an array?

  • 2011-05-04 04:48:54
  • a5his
  • 165155 View
  • 245 Score
  • 17 Answer
  • Tags:   ruby arrays

47 Answered Questions

[SOLVED] Convert form data to JavaScript object with jQuery

26 Answered Questions

[SOLVED] Convert JS object to JSON string

24 Answered Questions

[SOLVED] Safely turning a JSON string into an object

  • 2008-09-05 00:12:01
  • Matt Sheppard
  • 1153256 View
  • 1199 Score
  • 24 Answer
  • Tags:   javascript json

14 Answered Questions

[SOLVED] A concise explanation of nil v. empty v. blank in Ruby on Rails

  • 2009-05-19 22:51:36
  • Arrel
  • 282025 View
  • 1017 Score
  • 14 Answer
  • Tags:   ruby-on-rails ruby

10 Answered Questions

[SOLVED] Understanding the Rails Authenticity Token

33 Answered Questions

[SOLVED] How do I get the current absolute URL in Ruby on Rails?

7 Answered Questions

[SOLVED] How to convert a string to lower or upper case in Ruby

Sponsored Content