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

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

@Vishwas Nahar 2019-02-08 19:23:32

Using this '[88,89,100]'.scan(/\d/) returns ["8", "8", "8", "9", "1", "0", "0"]

@shivam 2019-02-11 12:42:16

@VishwasNahar tweaking pattern to \d+ will solve this. I have updated my answer. Thanks

@shivam 2019-02-11 12:43:54

PS: you should definitely use JSON.parse @VishwasNahar

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

@M. Habib 2019-03-25 09:59:16

this one should be the accepted answer considering its votes

@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.

@Vishwas Nahar 2019-02-08 19:28:33

With using '["12", "45"]'.tr('[]','').map(&:to_i) it return error : undefined method map

@Ho Man 2019-02-08 20:03:57

tbh, at this point, you should just use JSON.parse lol. But if you reallyyyyy wanted, '["12", "45"]'.tr('["]','').split(',')

Related Questions

Sponsored Content

25 Answered Questions

[SOLVED] Safely turning a JSON string into an object

  • 2008-09-05 00:12:01
  • Matt Sheppard
  • 1175308 View
  • 1225 Score
  • 25 Answer
  • Tags:   javascript json

24 Answered Questions

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

  • 2009-12-31 17:49:03
  • user211662
  • 737500 View
  • 1195 Score
  • 24 Answer
  • Tags:   ruby arrays

29 Answered Questions

[SOLVED] Convert JS object to JSON string

47 Answered Questions

[SOLVED] Convert form data to JavaScript object with jQuery

8 Answered Questions

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

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
  • ashis
  • 170349 View
  • 253 Score
  • 17 Answer
  • Tags:   ruby arrays

14 Answered Questions

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

  • 2009-05-19 22:51:36
  • Arrel
  • 288968 View
  • 1036 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?

Sponsored Content