From: "Jesús Gabriel y Galán" Date: 2007-09-28T17:19:49+09:00 Subject: Re: how to do "do" blocks On 9/28/07, Daniel Talsky 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.