Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string into Array in rails

Tags:

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]
like image 967
Ghulam Jilani Avatar asked Jan 26 '16 07:01

Ghulam Jilani


People also ask

How do I convert a string to an array in Ruby?

Strings can be converted to arrays using a combination of the split method and some regular expressions. The split method serves to break up the string into distinct parts that can be placed into array element. The regular expression tells split what to use as the break point during the conversion process.

What is %W in Ruby?

%w(foo bar) is a shortcut for ["foo", "bar"] . Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them. You can find a list of ways of writing literals in zenspider's quickref.

How do you split a string in Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.


2 Answers

Perhaps this?

   s.tr('[]', '').split(',').map(&:to_i)
like image 32
Ho Man Avatar answered Sep 23 '22 13:09

Ho Man


require 'json'

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

JSON.parse "[[1,2],3,4]"
  #=> [[1, 2], 3, 4] 
like image 151
Cary Swoveland Avatar answered Sep 21 '22 13:09

Cary Swoveland