From: Jim Weirich Date: 2006-03-17T22:01:40+09:00 Subject: Re: Card tricks with Ruby francisrammeloo@hotmail.com wrote: >>> cards = cards.sort_by { rand } > > How does this work?? > I thought the code block should yield either -1, 0 or +1, but rand > yields a number between 0 and 1. Or am I mistaken? > You are thing of the normal sort method which looks like this: cards.sort { |a, b| (a.suit <=> b.suit).nonzero? || (a.value <=> b.value) } With sort_by, you need to return a key value that will be used as the comparison key for that particular value. cards.sort_by { |card| [card.suit, card.value] } Sort_by actually does a "Schwartzian Transform"[1] on the array to perform the sorting. -- -- Jim Weirich [1] A trick developed by Randall Schwartz to speed sorting in Perl. See http://en.wikipedia.org/wiki/Schwartzian_Transform -- Posted via http://www.ruby-forum.com/.