[ruby-it] Hash con due elementi come chiave

Andrea Campi andrea.campi a zephirworks.com
Ven 5 Dic 2008 17:52:36 CET


On Fri, 5 Dec 2008 16:03:14 +0100, Njna Njna wrote:
> andrea riesci a farmi un esempio di come faresti tu? cosė mi schiarisco 
> le idee che ho un sacco di confusione
> grazie mille

class Itinerario
  def initialize(args = {})
    @a = args
  end
  
  def from
    @a[:from]
  end
  
  def to
    @a[:to]
  end
  
  def eql?(other)
    return self.from == other.from && self.to == other.to
  end
  
  def hash
    return (self.from.hash << 16) | self.to.hash
  end
end


Facendo cosė puoi scrivere:

strade = {}
strade[Itinerario.new(:from => 'Milano', :to => 'Roma')] = 650

# o anche

s = {
  Itinerario.new(:from => 'Milano', :to => 'Roma') = 650 # sovrascrive 
quello precedente
  Itinerario.new({:from => 'Milano', :to => 'Brescia'}) => 50,
  Itinerario.new({:from => 'Roma', :to => 'Milano'}) => 700
 }
strade.merge!(s)

puts strade.inspect


La cosa pių comoda č che se un domani vuoi supportare anche il caso di 
Milano -> Roma via Ancona, cambi solo la classe Itinerario e hai fatto.

Ciao,
  Andrea


More information about the Ml mailing list