M
Maarten Mortier
Is it possible to filter blocks, online, in an elegant way?
for instance if I have the block
class Integer
def divisors
(1..self).each{ |i| yield i if self % i == 0 }
end
end
and I want to pass this block through an 'online' filter.
I want to do something elegant like
10.divisors.odd{ |n| puts n }
# instead of
10.divisors{ |n| puts n if n.odd? } #, which is pretty much the same as
10.divisors{ |n| yield n if n.odd? }{|n| puts n}
I suppose it's not possible at all to treat a block as an object in this
manner?
If so, suppose I want to use a generic filter that takes a block and a
condition as its arguments, and returns the block of each elements for
which a condition is fulfilled?
# pseudo
def filter (block, condition)
block do |s|
yield s if s.condition
end
end
How would I do anything like this, without using arrays as inbetweens?
Am I again trying to treat blocks wrongly as objects, is it at all
possible to 'operate' through them in this way?
I'm new to ruby so this might be a bit stupid. I was just experimenting
and couldn't find an elegent, modular manner of filtering blocks
run-time in a 'chain-like' manner, without needlessly compressing them
to arrays in between.
I got this when googling, btw: www.rubyfilter.com
for instance if I have the block
class Integer
def divisors
(1..self).each{ |i| yield i if self % i == 0 }
end
end
and I want to pass this block through an 'online' filter.
I want to do something elegant like
10.divisors.odd{ |n| puts n }
# instead of
10.divisors{ |n| puts n if n.odd? } #, which is pretty much the same as
10.divisors{ |n| yield n if n.odd? }{|n| puts n}
I suppose it's not possible at all to treat a block as an object in this
manner?
If so, suppose I want to use a generic filter that takes a block and a
condition as its arguments, and returns the block of each elements for
which a condition is fulfilled?
# pseudo
def filter (block, condition)
block do |s|
yield s if s.condition
end
end
How would I do anything like this, without using arrays as inbetweens?
Am I again trying to treat blocks wrongly as objects, is it at all
possible to 'operate' through them in this way?
I'm new to ruby so this might be a bit stupid. I was just experimenting
and couldn't find an elegent, modular manner of filtering blocks
run-time in a 'chain-like' manner, without needlessly compressing them
to arrays in between.
I got this when googling, btw: www.rubyfilter.com