Mike Fletcher <lemurific+rforum / gmail.com> wrote:
> 
> In this case I could use
> 
> sorted_keys = data.sort_by { |k,v| [ v["lastname"], -1*v["age"] ] }
> 
> But what if I wanted reverse alphabetically by lastname (Z-A)?  In perl 
> I'd swap $a and $b in the first comparison, but I can't think of a 
> spiffy way to do the same using sort_by.

class Reverser
  attr_accessor :obj

  def initialize(obj)
    @obj = obj
  end
  
  def <=>(other)
    other.obj <=> self.obj
  end
end

class Object
  def rev
    Reverser.new(self)
  end
end

require 'yaml'

data = YAML.load %{
 Bobby:
   age: 11
   lastname: Smith
 Suzy:
   age: 13
   lastname: Jones
 Ted:
   age: 12
   lastname: Smith
}

p data

sorted_keys_0 = data.sort_by {|k,v| [v["lastname"].rev, v["age"]]}
sorted_keys_1 = data.sort_by {|k,v| [v["lastname"], v["age"].rev]}

p sorted_keys_0
p sorted_keys_1

martin