If I have
footnotes = { "apple" => "is a fruit", "cat" => "is an animal", "car" => "a transport"}
How can I get the index of these?, something like:
footnotes["cat"].index
# => 1
A Hash is a collection of key-value pairs. It is similar to an Array , except that indexing is done via arbitrary keys of any object type, not an integer index.
Overview. A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false .
You can find a key that leads to a certain value with Hash#key . If you are using a Ruby earlier than 1.9, you can use Hash#index . Once you have a key (the keys) that lead to the value, you can compare them and act on them with if/unless/case expressions, custom methods that take blocks, et cetera.
Ruby | Hash delete() function delete() is an Hash class method which deletes the key-value pair and returns the value from hash whose key is equal to key. Return: value from hash whose key is equal to deleted key.
There's no need to first retrieve the keys:
footnotes.find_index { |k,_| k== 'cat' } #=> 1
As to the question of whether hash key-value pairs have an index (since v1.9), I would just point out that the Ruby monks decided to supply us with Enumerable#find_index, which of course means Hash.instance_methods.include?(:find_index) #=> true
.
You can do
footnotes.to_a.index {|key,| key == 'cat'}
# => 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With