clemlatz
clemlatz

Reputation: 8053

Get the index of an element in an array of hashes with the maximum value for a particular attribute

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

Answers (2)

pangpang
pangpang

Reputation: 8821

have a try:

array.index(array.max_by { |i| i["updated_at"] })

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118261

You want then

<% selected = my_array.each_index.max_by { |i| my_array[i].updated_at } %>

Upvotes: 2

Related Questions