Skip to content

Instantly share code, notes, and snippets.

@SergeiStruk
Last active August 29, 2015 14:15
Show Gist options
  • Save SergeiStruk/4d9c1579e078e902e5e4 to your computer and use it in GitHub Desktop.
Save SergeiStruk/4d9c1579e078e902e5e4 to your computer and use it in GitHub Desktop.
#======== Ruby 1.9.3 ========================
# Order of items with duplicated values will change if array contains items with other values
1.9.3-p547 :036 > arr = [{:id=>1, :val=>30}, {:id=>2, :val=>30}, {:id=>1002, :val=>82}]
=> [{:id=>1, :val=>30}, {:id=>2, :val=>30}, {:id=>1002, :val=>82}]
1.9.3-p547 :037 > arr.sort{|x,y| x[:val] <=> y[:val]}.map{|x| x[:id]}
=> [1, 2, 1002]
1.9.3-p547 :038 > arr.sort{|x,y| y[:val] <=> x[:val]}.map{|x| x[:id]}
=> [1002, 2, 1]
# Order of items with duplicated values won't change if array doesn't contain items with other values
1.9.3-p547 :039 > arr = [{:id=>1, :val=>30}, {:id=>2, :val=>30}]
=> [{:id=>1, :val=>30}, {:id=>2, :val=>30}]
1.9.3-p547 :040 > arr.sort{|x,y| x[:val] <=> y[:val]}.map{|x| x[:id]}
=> [1, 2]
1.9.3-p547 :041 > arr.sort{|x,y| y[:val] <=> x[:val]}.map{|x| x[:id]}
=> [1, 2]
#======== Ruby 2.2.0 ========================
# Order of items with duplicated values won't change if array contains items with other values
2.2.0 :021 > arr = [{:id=>1, :val=>30}, {:id=>2, :val=>30}, {:id=>1002, :val=>82}]
=> [{:id=>1, :val=>30}, {:id=>2, :val=>30}, {:id=>1002, :val=>82}]
2.2.0 :022 > arr.sort{|x,y| x[:val] <=> y[:val]}.map{|x| x[:id]}
=> [1, 2, 1002]
2.2.0 :023 > arr.sort{|x,y| y[:val] <=> x[:val]}.map{|x| x[:id]}
=> [1002, 1, 2]
# Order of items with duplicated values won't change if array doesn't contain items with other values
2.2.0 :024 > arr = [{:id=>1, :val=>30}, {:id=>2, :val=>30}]
=> [{:id=>1, :val=>30}, {:id=>2, :val=>30}]
2.2.0 :025 > arr.sort{|x,y| x[:val] <=> y[:val]}.map{|x| x[:id]}
=> [1, 2]
2.2.0 :026 > arr.sort{|x,y| y[:val] <=> x[:val]}.map{|x| x[:id]}
=> [1, 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment