0

sorter.sort_by{|name, user_id| user_id} is not working. Even though the hash map sorter is sorted it prints unsorted hash.

I have append the name and user_id with the required condition in the hash map:

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 
0

1 Answer 1

1

sort_by returns the sorted array, it doesn't sort the array in place.

2.3.0 :001 > x = %w( aa aaa a )
 => ["aa", "aaa", "a"]
2.3.0 :003 > x.sort_by { |w| w.size }
 => ["a", "aa", "aaa"]
2.3.0 :004 > x
 => ["aa", "aaa", "a"]

It means you either write

print sorter.sort_by{|name, user_id| user_id} 

or you have to re-assign the result to sorter

sorter = sorter.sort_by{|name, user_id| user_id} 
print sorter
Sign up to request clarification or add additional context in comments.

3 Comments

user_id 5 and 6 are not sorted
@carletti [["Georgina", "10"], ["Richard", "11"], ["Chris", "12"], ["Michael", "15"], ["Ian", "16"], ["David", "25"], ["Alan", "31"], ["Lisa", "39"], ["Nora", "5"], ["Theresa", "6"]] this is output I am getting. You can see user_id with 5 and 6 are printed last
Because you are storing the ID as string, and "10" is sorted before "6". If you want them to be sorted as Integer (and not as strings), then you must convert them to Integer.

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.