0
sorter.sort_by{|name, user_id| user_id}
funktioniert nicht. Obwohl der Hash-Map-Sortierer sortiert ist, wird unsortierter Hash-Wert ausgegeben.Sortierung Hash in Ruby
Ich habe den Namen und user_id
mit dem gewünschten Zustand in der Hash-Karte anhängen:
require 'json'
class Numeric
def to_rad
self * Math::PI/180
end
end
def distance(lat2, lon2)
lat1=12.9611159
lon1=77.6362214
dLat = (lat2-lat1).to_rad;
dLon = (lon2-lon1).to_rad;
a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.to_rad) * Math.cos(lat2.to_rad) *
Math.sin(dLon/2) * Math.sin(dLon/2);
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
d = 6371 * c;
return d
end
file= File.read('customers.json')
data_hash= JSON.parse( file)
sorter = Hash.new
data_hash["customers"].each do |user|
latitude=user["latitude"].to_f
longitude=user["longitude"].to_f
$count=0
if (distance(latitude,longitude).to_f < 100.00)
name = user["name"]
user_id=user["user_id"]
sorter[name]=user_id
# print name," ",user_id
# print "\n"
end
#
end
sorter.sort_by{|name, user_id| user_id}
print sorter
User_id 5 und 6 sind nicht sortiert –
@carletti [[“ Georgina, 10, Richard, 11, Chris, 12, Michael, 15, Ian, 16, David "," 25 "], [" Alan "," 31 "], [" Lisa "," 39 "], [" Nora "," 5 "], [" Theresa "," 6 "]] ist dies Ausgabe bekomme ich. Sie können sehen, Benutzer-ID mit 5 und 6 sind gedruckt letzten –
Weil Sie die ID als String speichern, und "10" ist vor "6" sortiert. Wenn Sie möchten, dass sie als Integer (und nicht als Zeichenfolgen) sortiert werden, müssen Sie sie in Integer konvertieren. –