From: John Joyce Date: 2007-09-16T11:27:35+09:00 Subject: Re: Newbie help On Sep 15, 2007, at 8:10 PM, Jeremy Woertink wrote: > Ali Koubeissi wrote: >> Hey, I've started with Ruby two days ago, and I have some questions. >> >> 2- Why does a block has to be on the same line when passing argument? >> Like in the previous example: kitty_toys.sort_by { |toy| toy >> [:fabric] }. >> If I tried to move the block down, it won't work. Also, if someone >> could >> explain how does the argument get passed to the block. I mean, >> based on >> what? >> > Welcome to ruby. First to start the question about Symbols. Well, they > are used in hashes a lot, you could very well do { 'shape' => 'sock' } > and it works the same, but just to be consistent you use the object > as a > symbol and it's value as what ever else. There is a lot more to that, > and i'm sure someone else will reply to tell you that. > 2. A block doesn't have to be on the same line. > kitty_toys.sort_by do |toy| > toy[:fabric] > end > > notice it's on 3 lines, but with this small of a block it looks ugly. > > The argument gets passed to the block by means of the "slide" or the > pipes. Not sure if that was the answer you were looking for, but there > you go. To give further detail a block has two possible delimiter pairs { } or do end As far as the interpreter is concerned they're same. Two things to remember: 1. Single or multi-line blocks all have to begin with the delimiter on the same line as the method the block belongs to. an_object.a_method { is the same as an_object.a_method do The ending } or end can be on any following line. 2. By convention (but not enforced by the interpreter) { } is used for single line blocks (i.e. Ruby one-liners) and do end is used for multi-line blocks. Ruby is nice to you by often making parentheses optional (except where things get fuzzy and difficult to guess easily) and semicolon statement endings optional (unless you want to squeeze some statements together on a single line.