Nil in Ruby processing method invocation

Source: Internet
Author: User

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?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.