From: Siep Korteling Date: 2008-02-08T07:04:49+09:00 Subject: Re: info on block arguments Russell Me wrote: >>>>kitty_toys.sort_by { |toy| toy[:shape] }.each do |toy| >>>> puts "Blixy has a #{ toy[:shape] } made of #{ toy[:fabric] }" >>>> end > > ok, so i see that a sort is being performed on kitty toys with > "kitty_toys.sort_by". but what's the next bit about? namely: { |toy| > toy[:shape] }.each do |toy| I see that the sort is based on the shape > from toy[:shape] but how? and what is the "|toy|" before it doing? and > then i assume that the .each means do it for all the items, right? and > then... for each toy, output the puts bit? (which then get's sorted by > the sort_by)? > > Sorry to be a bother with something so trivial. Read the code from left to right -Ruby does too. "sort_by" knows how to sort, but it does not know what to sort on. The block { |toy| toy[:shape] } is a simple machine. It gets each element of Kitty_toys and immediatly puts a label on it, by means of "|toy|".(or |Cookie| or whatever). Then it goes to work on this toy- It gets the :shape from it, and gives it to sort_by. sort_by does it's magick, which Gary Wright explains better than I can. The result is an array, sorted on shape. This (nameless) array is also iterated, this time with .each . This method .each does not know anything, it just executes the block for each element . The block again labels each element with "|toy|" . This not the same thing as the "toy" in de first block, which is finished and does not exist anymore anyway. "|sorted_toy|" might have been more clear. Then it goes to work on it: puts "Blixy has a #{ toy[:shape] } made of #{ toy[:fabric] }" in which "Puts"does the printing. If it encounters #{ toy[:shape] } puts pauses the printing and ruby executes what's in the curly braces. That's it. If you add "p kitty_toys" at the end of the code you'll see that kitty_toys is still unsorted. The unnamed sorted array has done it's work and disappeared. Regards, Siep -- Posted via http://www.ruby-forum.com/.