We often deal with code like this:
Name=person?person.name:nil
Take a property of an object, first determine whether the object is nil, not nil return the object property, otherwise return nil. This kind of code is more disgusting, is there a more interesting way to reduce the code? The author gives a piece of code:
Module Objectextension
def nil_or
return self unless self.nil?
o = object.new
Class << O
def method_missing (Sym, *args); Nil End
End
O
End
End
Class Object
Include Objectextension
End
The above code adds an extension to object, adding a Nil_or method to each instance of the objects, analyzing the method: If the object is not nil, return self (i.e. the object itself) immediately, or else generate a new object that passes through the Method_ The missing mechanism returns all of the method calls nil (the original is Class.new, the generated class will not be GC, here uses the reply-given scheme, generates the object, does method_missing on the object's Metaclass). So now the code can be written:
Is name=person.nil_or.name quite a DSL?