Fwd: how to do "do" blocks

I posted this earlier, but it didn’t get through… (see my other post
“Ac Cautionary Tale”).

hehe

SM

---------- Forwarded message ----------
From: Simon M. [email protected]
Date: Sep 28, 2007 10:32 AM
Subject: Re: how to do “do” blocks
To: [email protected]

Hey

The “do…end” and “{…}” are almost equivalent (although “{…}” has
higher precedence).

So,

collection_of_objects = []
10.times do
collection_of_objects << MyObject.create
end

Is the equivalent to:

collection_of_objects = []
10.times {
collection_of_objects << MyObject.create
}

But (from the Ruby Cookbook), you may need to look at precedence.

So,

1.upto 3 do |x|
puts x
end

is ok.

But,

1.upto 3 { |x|
puts x
end

is not, as the code block binds to the 3, not the function call.

So, it would have to be:

1.upto(3) { |x|
puts x
end

Hope this helps!

SM

On 9/28/07, Daniel T. [email protected] wrote:

10.times do { collection_of_objects << MyObject.create }

I didn’t understand there was ANY difference between the two syntaxes
really. Can someone explain to me the finer points?

Posted via http://www.ruby-forum.com/.


Simon M.

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