From: Wybo Dekker Date: 2006-02-05T22:16:54+09:00 Subject: Re: how to vary sort's block? Thanks all for the very valuable explanations and suggestions. I finally came to the conclusion that, for my problem (to do a sort, depending on the value of some variable `order'), sort_by is the most versatile way. I saved an example for future reference, which may be useful for others on the list: #!/usr/bin/ruby class Thing attr_reader :name,:amount def initialize(name,amount) @name,@amount = name,amount end def list puts ['',@name,@amount].join("\t") end end arr = [ Thing.new('Johnny',20), Thing.new('Anny',20), Thing.new('John',10), Thing.new('Anny',10), Thing.new('John',30), Thing.new('Anny',30), ] for order in [:name, :amount] puts "by #{order}:" arr.sort_by{|x| x.send(order)}.each {|a| a.list} end order = :name puts "by #{order}_length, #{order}, amount:" arr.sort_by{|x| [ x.send(order).length, x.send(order), x.amount ] }.each {|a| a.list} PS. Good to see in the definition of arr that the extra comma after the last element is not an error anymore. -- Wybo