I'm trying to get the keys, but why values appear?

I’m trying to write a script that lists ONLY the keys in a hash as
follows: http://pastie.org/private/1ruahb5w05ihsloqwmqeng

The case is that when I run the script, I get the following:

NameAbder-Rahman A.

While, I’m intending to get


What am I missing in the script?


On Tuesday 13 July 2010, Abder-rahman Ali wrote:

|What am I missing in the script?

As you can see from the documentation (for example, with ri Hash#each),
Hash#each yields two arguments to the block: the key and the
value. Since your block only takes one argument, ruby puts both in an
whose to_s method produces a string with the two elements one after the

If you only want the key, you can use each_key rather than each, since
will only pass the block the keys:

personal_information.each_key{|k| puts k}

If you want to use each (but you don’t need to in your example), you can
the block take two parameters and only use the first (the key):

personal_information.each{|key, val| puts key}

or have the block take a single argument (which will be an array) and
use only
the first entry of the array

personal_information.each{|i| puts i[0]}

I hope this helps


On Tue, Jul 13, 2010 at 4:40 PM, Abder-rahman Ali
[email protected] wrote:

What am I missing in the script?

the fun :slight_smile:

personal_information.each {|key| p key}
[“Name”, “Abder-Rahman A.”]
[“Age”, “26”]

personal_information.each {|key| p key.first}

personal_information.each_key {|key| p key}

personal_information.each_value {|key| p key}
“Abder-Rahman A.”

personal_information.each {|key,value| p key}

personal_information.each {|key,value| p value}
“Abder-Rahman A.”

kind regards -botp

Thanks a lot all for your replies. It really helps.

If you want the keys only you can do this
“personal_information.keys.each do |key|” or
“personal_information.each_key do |key|”

This, however, “personal_information.each do |key|” returns each
element of the hash as an array in the form [key, value]

Look here for the documentation (
class Hash - RDoc Documentation ), in fact this should
be the first place you look when you have a problem.