0

Continuing from where I've left off, I want to limit the number of postcodes (only select up to x, but for now, say 4).

point_a = Geokit::Geocoders::GoogleGeocoder.geocode "se18 7hp"

alpha = ["cr0 3rl", "W2 1AA", "abc 234", "aol 765", "wv1 111"]

miles = alpha.map do |m| point_a.distance_to(m) end
#=> an array of numbers in miles

The answer to return the nearest postcode was with: alpha[miles.index(miles.min)]

I am trying to return the nearest 4:

alpha[miles.index(miles[0..3].min)] # surely not possible

The question is, how to return an array of the nearest 4 postcodes?

Community
  • 1
  • 1
Sylar
  • 11,422
  • 25
  • 93
  • 166

1 Answers1

1

You can use sort_by:

alpha.sort_by{|m| point_a.distance_to(m)}.take(4)

Or with Ruby 2.2.0+, min_by with argument :

alpha.min_by(4){|m| point_a.distance_to(m)}
potashin
  • 44,205
  • 11
  • 83
  • 107
  • I was going to correct you there as I needed the range. +1 for the docs. Thanks. – Sylar Feb 29 '16 at 08:45
  • 1
    @Sylar: Well, you can `select` elements that have `point_a.distance_to` within `1..3` miles and then use the code I've posted – potashin Feb 29 '16 at 08:47