Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get keys from hash - ruby c extension

I am looking for a function which can get me all the keys from hash or I can loop through the hash to retrieve single key at a time.

Currently I am hardcoding key

VALUE option = rb_hash_aref(options, rb_str_new2("some_key"));
like image 996
mandss Avatar asked Dec 10 '14 16:12

mandss


People also ask

How do you get the key of a hash in Ruby?

Ruby | Hash key() functionHash#key() is a Hash class method which gives the key value corresponding to the value. If value doesn't exist then return nil.

What does .keys do in Ruby?

In Ruby, the key() method of a hash returns the key for the first-found entry with the given value. The given value is passed as an argument to this method.

Can a hash have duplicate keys Ruby?

Short answer is no, hashes need to have unique keys.


2 Answers

You can iterate over the key/value pairs with a callback function using rb_hash_foreach (blog post w/an example):

void rb_hash_foreach(VALUE, int (*)(ANYARGS), VALUE);

There is an rb_hash_keys in MRI, but it's not in any header files it seems, so using it may be risky.

like image 91
Nick Veys Avatar answered Nov 15 '22 10:11

Nick Veys


You could always make a call to the Ruby method itself:

VALUE keys = rb_funcall(hash, rb_intern("keys"), 0)
like image 34
thomthom Avatar answered Nov 15 '22 10:11

thomthom