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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.