why the lucky stiff wrote:
My 1.8.0 summary is up at:
http://whytheluckystiff.net/articles/2003/08/04/rubyOneEightOh
I’m about halfway done. I’ll post a link again when I feel like I’m
finished.
One thing mentioned there is the new sort_by in Enumerable. A simple example I tried is:
text = [“the”, “quick”, “brown”, “fox”, “jumps”, “over”, “the”, “lazy”, “dog”]
puts text.sort_by { |x| x.length }.inspect
#=> [“the”, “the”, “fox”, “dog”, “over”, “lazy”, “quick”, “brown”, “jumps”]
Something that’s not mentioned, but I figured I’d try it, because I thought it would be nifty, is sorting by multiple values …
text = [“the”, “quick”, “brown”, “fox”, “jumps”, “over”, “the”, “lazy”, “dog”]
puts text.sort_by { |x| [x.length, x] }.inspect
#=> [“dog”, “fox”, “the”, “the”, “lazy”, “over”, “brown”, “jumps”, “quick”]
Ie, we now have the values sorted first by their length, and when the length is the same, they’re sub-sorted by the text itself. I think that’s great!
This would be particularly useful if the data items in the enumeration were instances of more complex objects. Then, you could do things like:
sorted = people.sort_by { |p| [p.last_name, p.first_name, p.salary] }
I just love Ruby!