Confused in array as key

I execute program following way:

dictionary = { ‘cat’ => ‘feline animal’, ‘dog’ => ‘canine animal’}
dictionary.each {|key, value| puts dictionary[key]}

Then I got output like:

feline animal
canine animal

My question is I used “puts dictionary[key]” so I got output like:

feline animal
canine animal

But these output is VALUE of (cat and dog). But as I used
“-------dictionary[key]” in second line of program so I should get key
of hash like (cat, dog).

I do not able to understand that.

Could anyone explain me?

Thank you.

Although it is not obvious, what you try to achieve, I venture, that you
should read about the method “keys” of the Hash-class :

ri Hash.keys

Do not talk about Hashes as if they were Arrays. Despite all similarity,
you use the one, where you do not want the other and we will understand
you much better.

Please give us an authentic code-example, as your line
puts dictionary[key]
is not authentic. ‘key’ is not defined, so we cannot know, what you
really do.

TY.

Dear Jaimin,

Your question is really confusing.
Could you please try to “rephrase it” (say it another way) showing
code examples so we can get a grab of what you’re trying to
accomplish?

I would give my try that you are talking about “array as key” as in
the foreach from PHP? Is it something about it?

dictionary = { ‘cat’ => ‘feline animal’, ‘dog’ => ‘canine animal’}

dictionary.class

=> Hash

So It’s a Hash, not an Array.

dictionary.keys

=> [“cat”, “dog”]

dictionary.values
=> [“feline animal”, “canine animal”]

dictionary.each do |key, value|
puts “The key is #{key} and the value is #{value}”
end

On Sun, Mar 9, 2014 at 9:23 AM, Abinoam Jr. [email protected] wrote:

dictionary = { ‘cat’ => ‘feline animal’, ‘dog’ => ‘canine animal’}
=> [“feline animal”, “canine animal”]

dictionary.each do |key, value|
puts “The key is #{key} and the value is #{value}”
end

Sorry for the cut e-mail

going on…

dictionary.each do |key, value|
puts “The key is #{key} and the value is #{value}”
end

It outputs

The key is cat and the value is feline animal
The key is dog and the value is canine animal

Best regards,
Abinoam Jr.

Abinoam Jr. wrote in post #1139301:

On Sun, Mar 9, 2014 at 9:23 AM, Abinoam Jr. [email protected] wrote:

dictionary = { ‘cat’ => ‘feline animal’, ‘dog’ => ‘canine animal’}
=> [“feline animal”, “canine animal”]

dictionary.each do |key, value|
puts “The key is #{key} and the value is #{value}”
end

Sorry for the cut e-mail

going on…

dictionary.each do |key, value|
puts “The key is #{key} and the value is #{value}”
end

It outputs

The key is cat and the value is feline animal
The key is dog and the value is canine animal

I rephrase my question.

Thank you

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs