Pensierinmusica
Pensierinmusica

Reputation: 6940

Ruby: two-dimensional arrays syntax

In Ruby, suppose we have a 2-dimensional array, why is this syntax fine:

array.each do |x|
  x.each do |y|
    puts y
  end
end

But this is not:

array.each{|x|.each{|y| puts y}}

Any ideas? Thanks

Upvotes: 0

Views: 281

Answers (2)

glenn mcdonald
glenn mcdonald

Reputation: 15478

If you replace your do...end blocks with {...} carefully you'll find that your second form works the same as your first. But puts array accomplishes the same thing as this whole double loop.

If I may offer some polite meta-advice, your two Ruby questions today seem like you maybe were asked to do some things in a language you don't know, and are frustrated. This is understandable. But the good news is that, compared to many other languages, Ruby is built on a very small number of pieces. If you spend a little time getting really familiar with Array and Hash, you'll find the going much smoother thereafter.

Upvotes: 0

denis-bu
denis-bu

Reputation: 3446

This should be fine array.each{|x| x.each{|y| puts y}}

You forget to refer x first.

I.e. . is supposed to be left associate operator. If you have noting on the left side - this is an error.

Upvotes: 4

Related Questions