In
Re: Crazy hash sorting issue., I posted a sieve() function that works to sift through a list and produce "layers" of data, as it were. The list is passed through a series of filters and ordered thus. Here's the
PerlRuby code (
update: the Perl code is in the node linked to at the beginning of this paragraph):
I alluded that the Ruby version of this looks nicer, and here was my first crack:
class Array
def sieve (*how)
call = block_given?
slots = Hash[]
how.push(Proc.new { true })
how.each { |h| slots[h] = [] }
self.each { |x|
i = (call == true) ? yield(x) : x
how.each { |h|
if h.call(i) == true
slots[h].push(x)
break
end
}
}
return how.collect { |h| slots[h] }.flatten
end
end
a = [6,5,2,4,3,1,7]
puts a.sieve(
Proc.new { |n| n < 5 },
Proc.new { |n| n < 10 }
) { |x| x * 2 }.inspect
The beauty of this Ruby code is that things are streamlined. I've made 'sieve' a method of Array, and due to the interesting nature of arguments in Ruby, I can pass it a list of Procs (code blocks) and then tack another code block at the end that describes how to transform the data before running it through the filters. I'm working on another version of this that allows me to say
sieve {block 1}.{block 2}.{block 3}.sift(array) {how}
So that I can produce a sieve and store it away:
this_sieve = sieve {b1}.{b2}.{b3}
# and then
this_sieve.sift(array) { how }
I am really fond of Ruby, but I only use it academically -- that is, I've never really found a reason to use it instead of Perl in the daily tasks I have.