I am building a hash into an array and then pushing each one into one big array. This works fine (I’m using Gmaps4Rails) but I’m wondering if there’s a more Ruby way to go about it?
def index
@allpoints = []
@links = Link.find([1, 2, 3])
@links.each do |link|
linkpoints = []
link.link_points.each do |pt|
linkpoints << { :lat => pt.latitude, :lng => pt.longitude }
end
@allpoints << linkpoints
end
@data = @allpoints.to_json
end
SOLUTION EDIT: (I went with the one below) Shorter than my original, yet good enough readability in my eyes:
def index
all_points = []
Link.find([1,2,3]).each do |link|
all_points << link.link_points.map { |pt| { lat: pt.latitude, lng: pt.longitude } }
end
@data = all_points.to_json
end
First: you don’t need to create tons of
@variables. The ones you don’t use in your views (local variables to your Controller’s action) should be classic local variables.Second: You could refactor your action like this:
Let me know if the code above doesn’t not have the expected behavior and the output.