Questions about how the program understands the Hash without really defining it


#1



I have problems in understanding the material in the course. For example, in chapter 7. Iterating Over the Hash there is a code provided:


fruit = {
  "apple" => 2,
  "banana" => 3,
  "cherry" => 5
}

fruit.each do |name, count|
  puts name + " " + count.to_s
end

It seems quite make sense to me... until, I start to think why the program knows

name refers to "apple", "banana", cherry", but not integer 2, 3, 5

From the example given by the course, it seems we did not really define the hash key name and hash key count before the iterator fruit.each. So, why we could use it directly -- without defining name refers to "apple" but not 2? Or is it because Ruby follows the order of the key-value pair when we decalre fruit = {}?


#2

Maybe some examples with outputs will give you some clearance.

    >> fruit.each { |name, count| puts name + " " + count.to_s }
    =>apple 2
    =>banana 3
    =>cherry 5

    >>fruit.each { |e| puts e }
    =>apple
    =>2
    =>banana
    =>3
    =>cherry
    =>5

    >>fruit.each_value { |v| puts v }
    =>2
    =>3
    =>5

    >>fruit.each_key { |k| puts k }
    =>apple
    =>banana
    =>cherry

    >>fruit.each_pair { |k, v| puts k + " " + v.to_s }
    =>apple 2
    =>banana 3
    =>cherry 5

.each_key and .each_value would work exactly as fruit.keys.each and fruit.values.each.
I hope you have some clearance now.


#3

Lot of thanks, tomegz.

You explain it very clear. Got it completely. I guess it would be fantastic if you write out the course instead of what I read in codecademy.

Thanks again, and have a nice day!


#4

Glad to help you! Make sure to visit http://ruby-doc.org every time you're in doubt! :slight_smile:


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.