Ruby Forum Italian Ruby user group > Il problema di Matteo all'RSC

Posted by Giovanni Intini (Guest)
on 25.09.2008 14:13
(Received via mailing list)
Ciao oggi da perfetto fancazzista ancora semiubriaco (3 bloody mary, 2
vodka tonic, 1 ginger&whiskey, 1 russian, 2 panini a caso) ho provato
a risolvere il problema proposto ieri da Matteo:

"Ho un array di tre categorie di elementi, come lo partiziono in un
solo passaggio?"

La mia soluzione (comprensiva di due test, giusto per essere
ridondante) è qui: http://pastie.org/279258

Qualcuno ha una soluzione più bella?
Posted by Luca Guidi (Guest)
on 25.09.2008 14:15
(Received via mailing list)
%w(m m f g f m f g m m g f).sort
  #=> ["f", "f", "f", "f", "g", "g", "g", "m", "m", "m", "m", "m"]
Posted by Giovanni Intini (Guest)
on 25.09.2008 14:19
(Received via mailing list)
In un passaggio.

Il giorno 25/set/08, alle ore 14:15, Luca Guidi ha scritto:
Posted by Giovanni Intini (Guest)
on 25.09.2008 14:19
(Received via mailing list)
E inoltre, se sono elementi diversi, tipo numeri che finiscono per 9,
numeri che finiscono per 3 e stringhe, sort non va bene.
Il giorno 25/set/08, alle ore 14:15, Luca Guidi ha scritto:
Posted by Luca Guidi (Guest)
on 25.09.2008 14:24
(Received via mailing list)
Giovanni Intini wrote:
> E inoltre, se sono elementi diversi, tipo numeri che finiscono per 9,  
> numeri che finiscono per 3 e stringhe, sort non va bene.
Già stai a cambiare le specifiche? :P
PS: Esiste anche #sort_by ;)
Posted by Giovanni Intini (Guest)
on 25.09.2008 14:25
(Received via mailing list)
Le specifiche parlavano di elementi, io ho solo fatto un test con
caratteri :)

E anche sort_by non lo fa in un solo passaggio.

Il giorno 25/set/08, alle ore 14:23, Luca Guidi ha scritto:
Posted by Claudio Petasecca Donati (etapeta)
on 25.09.2008 14:53
Con Ruby 1.9 (credo) possiamo sfruttare il metodo group_by, che e' 
definito anche in Rails:

>> pool = %w(m m f g f m f g m m g f)
=> ["m", "m", "f", "g", "f", "m", "f", "g", "m", "m", "g", "f"]
>> pool.group_by {|x| x}.values.flatten
=> ["m", "m", "m", "m", "m", "f", "f", "f", "f", "g", "g", "g"]

Per versioni di ruby precedenti, si puo' definire il metodo group_by:

module Enumerable
  def group_by
    assoc = Hash.new
    each do |element|
      key = yield(element)
      if assoc.has_key?(key)
        assoc[key] << element
      else
        assoc[key] = [element]
      end
    end
    assoc
  end
end
Posted by Tucano (Guest)
on 25.09.2008 15:00
(Received via mailing list)
On Sep 25, 2008, at 2:53 PM, Claudio Petasecca Donati wrote:

> Con Ruby 1.9 (credo) possiamo sfruttare il metodo group_by, che e'
> definito anche in Rails:


anche ruby 1.8.7