One of the advanced OOP features of Ruby Way

Source: Internet
Author: User
Tags sort

1 send a message to an object

When you call a method, you send a message to an object, and in Ruby we can decide which method is invoked at runtime. This is what the Send method does, and he accepts a symbol as an argument.

For a simple example, suppose we want to write a sort, we want to use a different domain as the key for comparison. Although we can use block at this time, if we use send, we can have a more graceful way of writing:

Java code

Class Person
Attr_reader:name,: Age,: Height
def initialize (name, age, height)
@name, @age, @heig HT = name, age, the height end
def Inspect #
@name # @age # @height '
end

  class Array
def sort_by (sym) # Our own version of Sort_by
self.sort {|x,y| x.send (sym) <=> y.send (SYM)}
End
people = []
people << person.new ("Hansel",)
people << ; Person.new ("Gretel",)
people << person.new ("Ted",)
people << person.new ("Alice", 33 ,
p1 = people.sort_by (: name)
P2 = people.sort_by (: Age)
p3 = people.sort_by (: height)

  p P1 # [Alice, Gretel, Hansel, Ted]
p p2 # [Gretel], Alice, Hansel, Te D c]
p P3 # [Alice, Gretel, Ted, Hansel 35 69]        

__send__ is actually the alias of the Send method. However, it is recommended to use __SEND__, because send has the potential to be defined as a user's own method.

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.