Kurt StephensNerd Up! | ||
|
Kurt on Sat, 2007-08-04 03:42.
A long time ago, in Objective-C on the NeXT, one could often remove How many times have we seen this in Ruby?: def foo
bar && bar.baz && bar.baz.caz("x")
end
Or even worse, avoiding redundant execution?:
def foo
(temp = @bar) &&
(temp = temp.baz) &&
temp.caz("x")
end
In Objective-C this could be written as:
- foo {
return [[bar baz] caz: "x"];
}
So in Ruby:
class ::NilClass
def method_missing(*args)
nil
end
end
@bar = nil
def foo
@bar.baz.caz("x")
end
foo
# => nil
Assuming that most of the time An additional benefit is that Obviously, it breaks code that expects exceptions to be thrown for messages to Introduce a method that explicitly checks for nil:
module ::Kernel
def not_nil; self; end
end
class ::NilClass
def not_nil; raise("not_nil failed"); end
end
@bar = nil
def foo
@bar.baz.caz("x").not_nil
end
foo
# => RuntimeError: not_nil failed
Comments? Reply |
||
Recent comments
2 weeks 4 days ago
6 weeks 6 days ago
16 weeks 6 days ago
18 weeks 3 days ago
20 weeks 6 days ago
20 weeks 6 days ago
24 weeks 1 day ago
24 weeks 1 day ago
26 weeks 7 hours ago
26 weeks 3 days ago