Last active
November 20, 2019 23:46
-
-
Save jnst/2205a3ef4d92701a7bceef215b70e1cc to your computer and use it in GitHub Desktop.
Difference of max and max_by in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
array = [ | |
{ id: 1, lv: 56 }, | |
{ id: 2, lv: 12 }, | |
{ id: 3, lv: 38 }, | |
{ id: 4, lv: 99 }, | |
{ id: 5, lv: 27 }, | |
] | |
p array.max { |a, b| a[:lv] <=> b[:lv] } # => {:id:4, lv:99} | |
p array.max_by { |v| v[:lv] } # => {:id:4, lv:99} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
hash = { | |
a: { id: 1, lv: 56 }, | |
b: { id: 2, lv: 12 }, | |
c: { id: 3, lv: 38 }, | |
d: { id: 4, lv: 99 }, | |
e: { id: 5, lv: 27 }, | |
} | |
p hash.max { |(k1, v1), (k2, v2)| v1[:lv] <=> v2[:lv] } # => [:d, {:id=>4, :lv=>99}] | |
p hash.max_by { |(k, v)| v[:lv] } # => [:d, {:id=>4, :lv=>99}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment