Home > Net >  Find location of a value in a hash in Ruby
Find location of a value in a hash in Ruby

Time:01-28

I have a hash list and I want to find when a user gives a value if that value comes after or before a target key in the list. So for example I have the following list

my_list = {
key1 => value1,
key2 => value2,
key3 => value3,
key4 => value4
}

Then the user chooses key2 then it has a target key that was chosen let's say was key3

So my function will check if key2 comes before or after the target key, in this case key3.

If it was an array I would check which index the value is. But in a hash I am not sure how to do.

CodePudding user response:

You can create a simple sequence look-up table with almost zero effort:

MY_LIST = {
  start: 'Start',
  middle: 'Middle?',
  end: 'End!'
}

MY_LIST_SEQ = MY_LIST.keys.each_with_index.to_h

Now you have something that looks like this:

{:start=>0, :middle=>1, :end=>2}

Which means you can do this:

if MY_LIST_SEQ[a] > MY_LIST_SEQ[b]
  # ...
end

No need to use a linear scan each time you want to look something up.

  • Related