Skip to content

Instantly share code, notes, and snippets.

@jnst
Last active November 20, 2019 23:46
Show Gist options
  • Save jnst/2205a3ef4d92701a7bceef215b70e1cc to your computer and use it in GitHub Desktop.
Save jnst/2205a3ef4d92701a7bceef215b70e1cc to your computer and use it in GitHub Desktop.
Difference of max and max_by in Ruby
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}
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