Create a gist now

Instantly share code, notes, and snippets.

@jnst /array.rb
Last active May 15, 2017

What would you like to do?
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