Wednesday, July 28, 2010

Lazy evaluating with Enumerable#any?

Most of us know this:
1
2
3
4
5
6
7
8
class Awesome
def self.m1 ; true ; end
def self.m2 ; raise Exception ; end
end

# Case 1:
Awesome.m1 or Awesome.m2
# >> no error thrown

For some of us who likes Enumerable#any?, this won't work:
1
2
3
# Case 2:
[Awesome.m1, Awesome.m2].any?
# >> error thrown

That is because :m1 & :m2 are already evaluated before calling Enumerable#any?, to have lazy evaluation, we can do this:
1
2
3
# Case 3:
[:m1, :m2].any?{|m| Awesome.send(m) }
# >> no error thrown

For the perversive ones:
1
2
3
# Case 4:
Awesome.instance_exec { [:m1, :m2].any?{|m| send(m) } }
# >> no error thrown

No comments:

Post a Comment

Labels