Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the successor and predecessor of a hash key in Ruby 1.9?

Tags:

ruby

ruby-1.9

I wonder if something like this is possible without iterating over the whole hash:

collection = { red: 1000, green: 120, "yellow" => 1, blue: 999 }

Something like this:

collection.next_key(:red)    #Should return :green
collection.prev_key(:blue)   #Should return "yellow"

EDIT:: I was hoping to somehow access the fore and back member of the internal Ruby Hash data structure:

struct st_table_entry {
  unsigned int hash;
  st_data_t key;
  st_data_t record;
  st_table_entry *next;
  st_table_entry *fore, *back; // new in Ruby 1.9
};

(Source)

like image 536
Daniel Rikowski Avatar asked Nov 04 '22 10:11

Daniel Rikowski


1 Answers

I think that it will work

class Hash
  def next_key(key)
    self.keys[self.keys.find_index(key) + 1]
  end
  def prev_key(key)
    self.keys[self.keys.find_index(key) - 1]
  end
end

But remember that is Hash so order of items can be different from that one you write.

like image 71
Hauleth Avatar answered Nov 15 '22 07:11

Hauleth