Charlie Davies
Charlie Davies

Reputation: 1834

A string (thats looks like an array) into an array Ruby

I have an output from an API that look like this... (its a string)

[[2121212,212121,asd],[2323232,23232323,qasdasd]]

Its a string - not an array. I want to convert it to an array and then extract the first two elements in each array in the nested array to:

[2121212,212121],[2323232,23232323]

What's the best way to do this ruby? I could use regexp and extract - but basically the string is already an array, however the class is a string.

I tried

array.push(response)

but that just put the string in to the array as one element. I guess what would be nice is a to_array method

Upvotes: 1

Views: 1248

Answers (3)

Patrick Oscity
Patrick Oscity

Reputation: 54734

Assuming this is a JSON response (and if so, it is badly malformed and you should talk to the people that are responsible for this) you could write something like:

require 'json'

input= '[[2121212,212121,Asd],[2323232,23232323,qasdasd]]'
input.gsub!(/([A-Za-z ]+)/,'"\1"')
json = JSON.parse input
output = json.map{|x| x[0...2]}
p output

this prints

[[2121212, 212121], [2323232, 23232323]]

Upvotes: 0

peter
peter

Reputation: 42207

You will need to use regular expression anyway if not eval (shrudder...), this is the shortest one

str = "[[2121212,212121,asd],[2323232,23232323,qasdasd],[2424242,24242424,qasdasd]]"
p str.scan(/(\d+),(\d+)/)

=>[["2121212", "212121"], ["2323232", "23232323"], ["2424242", "24242424"]]

Upvotes: 2

Soundar Rathinasamy
Soundar Rathinasamy

Reputation: 6728

Using eval is very bad but I have no other easy option.

test_str = "[[2121212,212121,asd],[2323232,23232323,qasdasd]]"
test_str.gsub!(/([a-z]+)/) do
  "'#{$1}'" 
 end
 => "[[2121212,212121,'asd'],[2323232,23232323,'qasdasd']]"
test_array = eval(test_str)
 => [[2121212, 212121, "asd"], [2323232, 23232323, "qasdasd"]]
test_array.each do |element|
  element.delete(element.last)
end
 => [[2121212, 212121], [2323232, 23232323]]

Upvotes: 0

Related Questions