Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the index of a key in a ruby hash? [closed]

Tags:

ruby

hash

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
like image 833
Javier Giovannini Avatar asked Mar 11 '15 14:03

Javier Giovannini


People also ask

Do hashes have indexes Ruby?

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.

How do you check if a key-value exists in a hash Ruby?

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 .

How do I get the key-value in Ruby?

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.

How do you remove a key from a hash in Ruby?

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.


2 Answers

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.

like image 107
Cary Swoveland Avatar answered Sep 28 '22 05:09

Cary Swoveland


You can do

footnotes.to_a.index {|key,| key == 'cat'}
# => 1
like image 30
Santhosh Avatar answered Sep 28 '22 07:09

Santhosh