# How to know Array if have key?

**URL:** <https://www.ruby-forum.com/t/how-to-know-array-if-have-key/172233>\
**Category:** Ruby\
**Created:** [July 17, 2009, 6:09am UTC](https://www.ruby-forum.com/t/how-to-know-array-if-have-key/172233 "2009-07-17T06:09:39Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![rubyernewbie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/9dc877/32.png) [@rubyernewbie](https://www.ruby-forum.com/u/rubyernewbie)\
**Post date:** [July 17, 2009, 6:09am UTC](https://www.ruby-forum.com/t/how-to-know-array-if-have-key/172233/1 "2009-07-17T06:09:39Z")

</div>

a\_array= [{“1”=\>“11”}, {“2”=\>“22”}]  
how to test if a\_array have a key “11”???

---

<div class="post-metadata">

**Author:** ![rubyernewbie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/9dc877/32.png) [@rubyernewbie](https://www.ruby-forum.com/u/rubyernewbie)\
**Post date:** [July 17, 2009, 6:30am UTC](https://www.ruby-forum.com/t/how-to-know-array-if-have-key/172233/2 "2009-07-17T06:30:56Z")

</div>

Zhenning G. wrote:

> a\_array= [{“1”=\>“11”}, {“2”=\>“22”}]  
> how to test if a\_array have a key “11”???

Arrays don’t have keys, Hashes do.  
Here, you have an array with two elements.  
Both the elements are hashes. Neither hash has  
the key “11”, though the first has it as a value.

If you want to know whether a hash has a value,  
it’s slow; you have to search the hash, or extract  
all the values and check for the one you care about.

---

<div class="post-metadata">

**Author:** ![rubyernewbie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/9dc877/32.png) [@rubyernewbie](https://www.ruby-forum.com/u/rubyernewbie)\
**Post date:** [July 17, 2009, 7:49am UTC](https://www.ruby-forum.com/t/how-to-know-array-if-have-key/172233/3 "2009-07-17T07:49:48Z")

</div>

If you have a hash and you want to find whether or not a given value  
exists  
as a key you can use the “has\_key?” method

h = { “a” =\> 100, “b” =\> 200 }  
h.has\_key?(“a”) #=\> true  
h.has\_key?(“z”) #=\> false

---

<div class="post-metadata">

**Author:** ![rubyernewbie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/9dc877/32.png) [@rubyernewbie](https://www.ruby-forum.com/u/rubyernewbie)\
**Post date:** [July 17, 2009, 7:54am UTC](https://www.ruby-forum.com/t/how-to-know-array-if-have-key/172233/4 "2009-07-17T07:54:05Z")

</div>

thank you for help. clear.
