Rubyã§2次å é åãã½ã¼ããã
ç°¡åã«ã§ããã¾ã¨ãã¾ããã
ãããããã¨
ååæ¯ã®ååçªå·, ååå, ä¾¡æ ¼ãæã£ãä¸ã®ãããª2次å é åã«å¯¾ãã¦ãä¾¡æ ¼é ã¾ãã¯åååé ã®ã½ã¼ããè¡ãããã
shohin = [[1, "carrot", 88], [2, "tomato", 120], [3, "apple", 210], [4, "orange", 105]]
2次å é åãã½ã¼ãããä¾
ä¸ã®shohiné åã使ã£ã¦ã½ã¼ããè¡ãã
sorted = shohin.sort {|a, b| a[2] <=> b[2] # ä¾¡æ ¼ã½ã¼ã } p sorted # ã½ã¼ãçµæ # [[1, "carrot", 88], # [4, "orange", 105], # [2, "tomato", 120], # [3, "apple", 210]] sorted = shohin.sort {|a, b| a[1] <=> b[1] # åååã½ã¼ã } p sorted # ã½ã¼ãçµæ #[[3, "apple", 210], # [1, "carrot", 88], # [4, "orange", 105], # [2, "tomato", 120]]
- sortå¦çæã«a, bã«shohiné åã®ååæ¯ã®ãã¼ã¿ã渡ãããã
- a[x] <=> b[x] ã§xåç®ã®è¦ç´ (ååçªå· or ååå or ä¾¡æ ¼)ã®æ¯è¼ãè¡ãã並ã¹æ¿ããå®æ½ããã
- 並ã¹æ¿ããé åã¯sortedã«æ ¼ç´ãããã
åè
以ä¸ã®ãã¼ã¸ãåèã«ãã¾ããã
Rubyでオブジェクトを要素とする配列をソートする際の覚え。 - Dragonmasterの日記
ä»åã¯2次å é åã§ç¡çããã½ã¼ããã¾ãããããããã«æ¸ããªããªãã¸ã§ã¯ãããæ§é ä½ã§ãååããä½æããé åã§ç®¡çããæ¹ããã£ããã¾ã¨ã¾ãã¾ãã