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]
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.
%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.
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.
Perhaps this?
s.tr('[]', '').split(',').map(&:to_i)
require 'json'
JSON.parse "[1,2,3,4,5]"
#=> [1, 2, 3, 4, 5]
JSON.parse "[[1,2],3,4]"
#=> [[1, 2], 3, 4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With