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.