# Own method has\_key for class Hash. -howto

**URL:** <https://www.ruby-forum.com/t/own-method-has-key-for-class-hash-howto/171760>\
**Category:** Ruby\
**Created:** [July 8, 2009, 6:34pm UTC](https://www.ruby-forum.com/t/own-method-has-key-for-class-hash-howto/171760 "2009-07-08T18:34:21Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![koko](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/ee59a6/32.png) [@koko](https://www.ruby-forum.com/u/koko)\
**Post date:** [July 8, 2009, 6:34pm UTC](https://www.ruby-forum.com/t/own-method-has-key-for-class-hash-howto/171760/1 "2009-07-08T18:34:21Z")

</div>

Dear all,

Can you help me how can I implement my own “has\_key” method for “hash  
class.”

class Hash

def my\_each\_key(&block)  
self.each { |key|  
yield(key[0])  
}  
end

def my\_each\_value(&block)  
self.each { |value|  
yield(value[1])  
}  
end

def has\_key()  
#todo  
end

end

h = {1 =\> 1.0, 2 =\> 2.0, 3 =\> 3.0 }

many thanks in advance,

salai.

---

<div class="post-metadata">

**Author:** ![koko](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/ee59a6/32.png) [@koko](https://www.ruby-forum.com/u/koko)\
**Post date:** [July 8, 2009, 6:41pm UTC](https://www.ruby-forum.com/t/own-method-has-key-for-class-hash-howto/171760/2 "2009-07-08T18:41:58Z")

</div>

I was able able solve the problem …

def has\_key(k)  
self.each { |k|  
k = k[0]  
}  
return k  
end

is there any other better/easier solution?

regards,

salai.

---

<div class="post-metadata">

**Author:** ![koko](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/ee59a6/32.png) [@koko](https://www.ruby-forum.com/u/koko)\
**Post date:** [July 8, 2009, 8:06pm UTC](https://www.ruby-forum.com/t/own-method-has-key-for-class-hash-howto/171760/3 "2009-07-08T20:06:08Z")

</div>

At 2009-07-08 12:33PM, “salai” wrote:

> Dear all,
> 
> Can you help me how can I implement my own “has\_key” method for “hash class.”
> 
> class Hash  
> def my\_each\_key(&block)  
> […]  
> def my\_each\_value(&block)  
> […]  
> def my\_has\_key?(key)

```
      keys.include?(key)
```

---

<div class="post-metadata">

**Author:** ![koko](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/ee59a6/32.png) [@koko](https://www.ruby-forum.com/u/koko)\
**Post date:** [July 10, 2009, 6:12pm UTC](https://www.ruby-forum.com/t/own-method-has-key-for-class-hash-howto/171760/4 "2009-07-10T18:12:35Z")

</div>

thank you!.
