Skip to content

Instantly share code, notes, and snippets.

@satou-haruka-37
Created January 29, 2024 05:01
Show Gist options
  • Save satou-haruka-37/49746a062699821d0c89bcd48e53b4e4 to your computer and use it in GitHub Desktop.
Save satou-haruka-37/49746a062699821d0c89bcd48e53b4e4 to your computer and use it in GitHub Desktop.
Ruby Silver ハッシュのsort
a = {"Apple" => "Red color", "Orange" => "Orange color", "Banana" => "Yellow color", }
p a.sort{|n,m| n[1] <=> m[1]}
# ハッシュのsortでは一旦ハッシュを二次元配列に変換する
# [["Apple", "Red color"], ["Orange", "Orange color"], ["Banana", "Yellow color"]]
# n[1]の部分で、aには["Apple", "Red color"]のような要素が1つずつ入る
# その中のインデックス1番目ということは、a[1]の中身は、"Red color"となる(元々のキーと値のペアの、値の部分)
# 値が英語の文字列のため、それらをソートしてアルファベット順に並び替えられる。
#=>[["Orange", "Orange color"], ["Apple", "Red color"], ["Banana", "Yellow color"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment