Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

5
  • 3
    fastest if the array is very long Commented Nov 19, 2012 at 19:13
  • 18
    Depending on your use case this could be problematic if there are duplicate values. The method described above will return the equivalent or #rindex(last occurrence of value) To get #index equivalent results, meaning the hash returning the first index of the value you'd need to do something along the lines of reversing the array before creating the hash then subtracting the returned index value from the total length of the initial array - 1. # (array.length - 1 ) - hash['b'] Commented May 30, 2013 at 2:49
  • 3
    Doesn't the conversion into a hash take O(n) time? I suppose if it's going to be used more than once, then hash conversion will be more performant. but for single usage, is it no different then iterating through the array? Commented Sep 16, 2016 at 19:45
  • Yes, and probably worse for single use if it really matters as hash calculation won't short-circuit as quickly as a comparison. Commented Apr 23, 2018 at 17:49
  • If you have duplicate elements, @hololeap's answer is more complete. Commented Dec 28, 2021 at 14:35