2

I'm new to rubyonrails. I need to collect foreach element as below array format

[
  [lat1, long1],
  [lat2, long2],
  [lat3, long3],
  [lat4, long4]
]

my code is

@outlet.each do |outlets|
  lat = outlets.latitude
  long = outlets.longitude
end

i can collect lat,long every loop. How can i format those element in above format?

1
  • 1
    If these are ActiveRecord objects, you can use pluck to just fetched the attributes from the database, e.g. Outlets.where(...).pluck(:latitude, :longitude) Commented Sep 18, 2015 at 7:37

2 Answers 2

7

Use .map method (the result is what you want):

@outlet.map do |outlets|
  [outlets.latitude, outlets.longitude]
end
Sign up to request clarification or add additional context in comments.

4 Comments

could you please tell me, how can i render that array?
you can render the array as a json: render :json => @outlet.to_json
how do pass that format to a javascript, which is in view page?
@users4393829 <%= raw the_result_above_returned.to_json %> would do the job.
0

You also can use inject:

@outlet.inject([]) { |sum, outlets| sum << [outlets.latitude, outlets.longitude] }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.