Iterating over hases


#1

Hello coders,
I need to understand something about hash.

codeacademy wrote:

s = [[“ham”, “swiss”], [“turkey”, “cheddar”], [“roast beef”, “gruyere”]]

s.each do |sub_array|
sub_array.each do |y|

puts y
end
end

and I wrote it like this:

s = [[“ham”, “swiss”], [“turkey”, “cheddar”], [“roast beef”, “gruyere”]]

s.each {|x| puts x}

I can see the same result. Can you tell me if any difference between the code ?

Please share your experience.

Regards,
Momin


#2

Let’s consider some example comparisons…

Eg. 1.

s.each { |x| puts x }
["ham", "swiss"]
["turkey", "cheddar"]
["roast beef", "gruyere"]

Eg. 2.

s.each { |x| x.each { |y| puts y } }
ham
swiss
turkey
cheddar
roast beef
gruyere

Eg. 3.

s.each { |x| puts x.each { |y|  y } }
["ham", "swiss"]
["turkey", "cheddar"]
["roast beef", "gruyere"]

Eg. 4.

s.each { |x| print x.each { |y|  y } }
["ham", "swiss"]["turkey", "cheddar"]["roast beef", "gruyere"]

#3

So , is my code correct ?

Thanks for your valuable reply.

Regards,
Momin


#4

This is what the instructions ask for…

s.each do |sub_array|
  sub_array.each do |y|
    puts y
  end
end

which will give this output…

ham
swiss
turkey
cheddar
roast beef
gruyere

#5

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