Skip to content

Instantly share code, notes, and snippets.

@cschneid
Created April 5, 2015 00:51
Show Gist options
  • Save cschneid/140409f33a7a8d6705ee to your computer and use it in GitHub Desktop.
Save cschneid/140409f33a7a8d6705ee to your computer and use it in GitHub Desktop.
def min_by(ary, &fn)
first, *rest = ary;
min_elem, _ = rest.reduce([first, fn.call(first)]) do |(min_elem, min), new_elem|
if (new_min = fn.call(new_elem)) < min
[ new_elem, new_min ]
else
[ min_elem, min ]
end
end
min_elem
end
def min_by2(ary, &fun)
tups = ary.map {|x| [x, fun.call(x)] } # Make 2 tuples with the original value, and the mapped _by value
min = tups.inject(tups.first) { |(prev_x, prev_min), (x, candidate)| # Destructure the tuples
prev_min < candidate ?
[prev_x, prev_min] : [x, candidate] } # Rebuild the two tuple with the original value & the calculated min
min[0] # Get the original value back out of the 2 tuple
end
a = ["4", "1", "4", "3", "-1"]
puts min_by(a) { |x| x.to_i }
puts min_by2(a) { |x| x.to_i }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment