Ruby: Parsing a String Representation of Nested Arrays into an Array

Ruby: Parsing a string representation of nested arrays into an Array?

That particular example is being parsed correctly using JSON:

s = "[1,2,[3,4,[5,6]],7]"
#=> "[1,2,[3,4,[5,6]],7]"
require 'json'
#=> true
JSON.parse s
#=> [1, 2, [3, 4, [5, 6]], 7]

If that doesn't work, you can try running the string through eval, but you have to ensure that no actual ruby code has been passed, as eval could be used as injection vulnerability.

Edit: Here is a simple recursive, regex based parser, no validation, not tested, not for production use etc:

def my_scan s
res = []
s.scan(/((\d+)|(\[(.+)\]))/) do |match|
if match[1]
res << match[1].to_i
elsif match[3]
res << my_scan(match[3])
end
end
res
end

s = "[1,2,[3,4,[5,6]],7]"
p my_scan(s).first #=> [1, 2, [3, 4, [5, 6]], 7]

Convert string representation of nested array to Array

You can use YAML.load:

require 'yaml'    
YAML.load(val1.delete ':').map{|x| x.map(&:to_sym)}
# => [[:one, :two], [:four, :one]]

Demonstration

And I guess I should be ready for downvotes, but you can use eval:

eval(val1).map{|x| x.map(&method(:eval))}
# => [[:one, :two], [:four, :one]]

Demonstration

Ruby convert string array to array object

That example string looks like JSON. Use JSON.parse to return a Ruby array:

require 'json'

JSON.parse("[\"Mt Roskill\", \"Sylvia Park\"]")
#=> ["Mt Roskill", "Sylvia Park"]

How do I convert a string to an array of arrays?

How about the following?

require 'json'
arr = JSON.parse("[[1, 2], [3, 4], [5, 6]]") # => [[1, 2], [3, 4], [5, 6]]
arr[0] # => [1, 2]

Rails Array In A String

Just do eval('["a", "b", "c"]')

A nested array is changing to a string of values going from JavaScript to Rails

We are using leaflet, but we are doing something quite similar: upon drawing a geometry we show a modal with a form, and we set a hidden text field to contain the geometry.

We are using postgis, so we immediately store the geojson representation in that hidden field. Not quite sure if that is possible using OpenLayers (pretty sure it is, just not finding it right away). But maybe that is not the easiest format for you? If you are using postgis and activerecord-postgis gem, you can just assign a geojson to a geometry.

But if not, you will have to parse a geojson yourself (which is not too hard, but definitely a little more complicated).

So, as mentioned in the comments: JSON is a much better exchange format, always used in API's as both JS and Rails handle it very well.

So in your JS you could write:

document.getElementById('year_snippet_extent').innerHTML = JSON.stringify(boxCoords);

and at the rails end you would convert it back to whatever was put it into it as follows:

box_coords = JSON.parse(params[:year_snippet_extent])


Related Topics



Leave a reply



Submit