0

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

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, indeed, maybe that's what he missed. I thought he was pondering on "why the syntax is not what I'd like it to be"? :)
Yeah, I just realized it after I've put my answer. Update it a bit.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.