1

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?

Community
  • 1
  • 1
clemlatz
  • 7,543
  • 4
  • 37
  • 51

2 Answers2

2

You want then

<% selected = my_array.each_index.max_by { |i| my_array[i].updated_at } %>
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
0

have a try:

array.index(array.max_by { |i| i["updated_at"] })
pangpang
  • 8,581
  • 11
  • 60
  • 96