From: Todd Benson Date: 2008-02-09T14:29:16+09:00 Subject: Re: info on block arguments On Feb 6, 2008 8:25 PM, Russell Me wrote: > I'm trying to pick up ruby and I'm impressed by all the cool stuff it > does out of the box. I'm reading a few books but i'm finding why's > poignant guide to ruby to be the most helpful and entertaining > (http://poignantguide.net/ruby). > > However, I'm a bit stuck understanding how block arguments work. in his > example: > > kitty_toys = [ > {:shape => 'sock', :fabric => 'cashmere'}, > {:shape => 'mouse', :fabric => 'calico'}, > {:shape => 'eggroll', :fabric => 'chenille'} > ] > > kitty_toys.sort_by { |toy| toy[:shape] }.each do |toy| > puts "Blixy has a #{ toy[:shape] } made of #{ toy[:fabric] }" > end > > I know what it does. I put it through irb and it works. But i don't > understand HOW it works, exactly. Mainly, the toy bit. I don't quite get > what role it plays in the code and how the code uses it. > > I've read up online and in both books I have, but, for whatever reason i > STILL cannot grasp block arguments and what role they play. > > Maybe I'm just brain farting here, but if anyone could lend some tips on > this I'd appreciate it. As others have pointed out, the #sort_by method _throws_ you a reference (doesn't have to be called "toy") and you do whatever you want with it. What your block _should_ do largely depends upon how the calling method works. In this case, #sort_by throws your block object references (one at a time) and you are supposed to give it back an object reference that is comparable (i.e. responds to the <=> method). At least, that's the way I understand it without reading the underlying code. A _very_ simple example... def simple yield 3 end simple {|i| puts i} Todd