Reputation: 8053
I have an array of hashes, each hash is like: {title: xxx, author: yyy, updated_at: zzz}
In an ERB template, I need to get the array key of the hash that as the biggest updated_at
value.
I already found about max_by
in Finding the element of a Ruby array with the maximum value for a particular attribute and did:
<% selected = my_array.max_by { |element| element.updated_at } %>
But what I need here is to get not the hash element itself, but its index in the array. How would I do that?
Upvotes: 1
Views: 252
Reputation: 118261
You want then
<% selected = my_array.each_index.max_by { |i| my_array[i].updated_at } %>
Upvotes: 2