Given a json array:
[{ "x":"5", "y":"20" },{ "x":"6", "y":"10" },{ "x":"50", "y":"5" }]
I’d like to find argmax(x), such that I can do puts argmax(arr, :arg => "x").y and get 5. How can I elegantly implement this in Ruby?
Edit: Clarified a bit. The idea is that you can specify the field of an element in a list that you want to maximize and the method will return the maximizing element.
I think you want
Enumerable#max_by. To getylike you’re saying, it would be:(Well, actually, you’ll want the numbers to be numbers instead of strings, since ’50’ sorts lower than ‘6’. But I think you get the idea. You can
to_ior do whatever processing you need in the block to get the “real” value to sort by.)