Jesús Gabriel y Galán
9/28/2007 8:20:00 AM
On 9/28/07, Daniel Talsky <danieltalsky@gmail.com> wrote:
> How come this works:
>
> collection_of_objects = []
> 10.times do
> collection_of_objects << MyObject.create
> end
>
> But this doesn't:
>
> collection_of_objects = []
> 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?
The reason is that "do" starts a block, and then inside the block the
{} are parsed as a hash literal:
irb(main):001:0> collection_of_objects = []
=> []
irb(main):002:0> 10.times do { collection_of_objects << MyObject.create }
irb(main):003:1> end
SyntaxError: compile error
(irb):2: odd number list for Hash
from (irb):3
from :0
You have to use only one form of block, either do...end or {}. The
convention seems to be to use do...end for multiline blocks, while {}
is used for one-liners.
irb(main):005:0> 10.times { collection_of_objects << Array.new }
=> 10
irb(main):006:0> collection_of_objects
=> [[], [], [], [], [], [], [], [], [], []]
Regards,
Jesus.