1. send messages to the object
We can directly send messages to objects:
Ruby Code
Copy code The Code is as follows: Class helloworld
Def say (name)
Print "hello,", name
End
End
HW = helloworld. New
HW. Send (: Say, "world ")
We usually use HW. Say ("world"), but send can work on private methods.
Not only does send makeProgramMore dynamic, let's look at an example:
We have defined a class person. We want an array containing the person object to be
Sort by any member data of person:
Ruby codeCopy codeThe Code is as follows: class person
Attr_reader: name,: age,: Height
Def initialize (name, age, height)
@ Name, @ age, @ Height = name, age, height
End
Def inspect
"# @ Name # @ age # @ height"
End
End
Any class in Ruby can be opened at any time, so that it can be written as beautiful as 2. days_ago.
Code, we open array and define a sort_by method:
Ruby code
Class Array
Def sort_by (sysm)
Self. Sort {| X, Y | X. Send (sym) <=> Y. Send (sym )}
End
End
Let's take a look at the running results:
Ruby code
People = []
People <person. New ("Hansel", 35, 69)
People <person. New ("Gretel", 32, 64)
People <person. New ("Ted", 36,68)
People <person. New ("Alice", 33, 63)
P1 = people. sort_by (: name)
P2 = people. sort_by (: age)
P3 = people. sort_by (: height)
P P1 # [Alice 33 63, Gretel 32 64, Hansel 35 69, Ted 36 68]
P P2 # [Gretel 32 64, Alice 33 63, Hansel 35 69, Ted 36 68]
P P3 # [Alice 33 63, Gretel 32 64, Ted 36 68, Hansel 35 69]
How can this result be obtained?
In fact, apart from sending, you should pay attention to attr_reader. attr_reader defines the name,
Age, heigh three methods, and the sort method in array only needs to provide a comparison method:
X. Send (sym) <=> Y. Send (sym) Get the property value of person through send, and then use <=> compare
2. Create an object
<Object
Ruby can not only open a class, but also open an object and add or customize features to this object without affecting
Other objects:
Ruby code
A = "hello"
B = "Goodbye"
Def B. upcase
Gsub (/(.) (.)/) ($1. upcase + $2)
End
Puts a. upcase # Hello
Puts B. upcase # Goodbye
We found that the B. upcase method was customized as our own.
If you want to add or Customize multiple features to an object, we do not want to do this with multiple def B. Method1 def B. method2.
We can adopt a more modular approach:
Ruby code
B = "Goodbye"
Class <B
Def upcase # create single method
Gsub (/(.) (.)/) {$1. upcase + $2}
End
Def upcase!
Gsub! (/(.) (.)/) {$1. upcase + $2}
End
End
Puts B. upcase # Goodbye
Puts B # Goodbye
B. upcase!
Puts B # Goodbye
This class is called Singleton class, because this class is for the object B.
Similar to the design pattern singleton object, Singleton only occurs once.
<Self: Add behavior to your defined class
Ruby code
Class theclass
Class <self
Def hello
Puts "Hello! "
End
End
End
Theclass. Hello # Hello!
<Self modified the class you defined for the class. This is a very useful technique. It can define the class level.
And then use it in other definitions of this class. The following column defines the access
Function, we want to convert all member data into strings during access. We can use this technology
Define a class-level method accessor_string:
Ruby code
Class myclass
Class <self
Def accessor_string (* names)
Names. Each do | Name |
Class_eval <-EOF
Def # {name}
@ # {Name}. to_s
End
EOF
End
End
End
Def initialize
@ A = [1, 2, 3]
@ B = time. Now
End
Accessor_string: A,: B
End
O = myclass. New
Puts o.a #123
Puts O. B # Fri Nov 21 09:50:51 + 0800 2008
Using the extend module to add behavior to your object, the methods in the module become
Instance method:
Ruby code
Module quantifier
Def any?
Self. Each {| x | return true if yield x}
False
End
Def all?
Self. Each {| x | return false if not yield x}
True
End
End
List = [1, 2, 3, 4, 5]
List. Extend (quantifier)
Flag1 = List. Any? {| X> 5} # False
Flag2 = List. Any? {| X> = 5} # True
Flag3 = list. All? {| X <= 10} # True
Flag4 = list. All? {| X % 2 = 0} # False
3. Create a parameterized class:
If we want to create many classes, these classes only have different initial values of class members, we can easily remember:
Ruby code
Class intelligentlife # wrong way to do this!
@ Home_planet = Nil
Def intelligentlife. home_planet
@ Home_planet
End
Def intelligentlife. home_planet = (X)
@ Home_planet = x
End
#...
End
Class Terran <intelligentlife
@ Home_planet = "Earth"
#...
End
Class Martian <intelligentlife
@ Home_planet = "Mars"
#...
End
This method is incorrect. In fact, class members in ruby are not only shared by all objects in this class,
In fact, it will be shared by the entire inheritance system, so we call Terran. home_planet and will output
"Mars", and what we expect is earth
A feasible method:
We can achieve the goal through class_eval latency evaluation during runtime:
Ruby code
Class intelligentlife
Def intelligentlife. home_planet
Class_eval ("@ home_planet ")
End
Def intelligentlife. home_planet = (X)
Class_eval ("@ home_planet =#{ x }")
End
#...
End
Class Terran <intelligentlife
@ Home_planet = "Earth"
#...
End
Class Martian <intelligentlife
@ Home_planet = "Mars"
#...
End
Puts Terran. home_planet # Earth
Puts Martian. home_planet # Mars
The best method:
Instead of using class variables, we use class instance variables:
Ruby code
Class intelligentlife
Class <self
Attr_accessor: home_planet
End
#...
End
Class Terran <intelligentlife
Self. home_planet = "Earth"
#...
End
Class Martian <intelligentlife
Self. home_planet = "Mars"
#...
End
Puts Terran. home_planet # Earth
Puts Martian. home_planet # Mars
Iv. continuations in ruby:
Continuations is probably the most difficult concept to understand in Ruby. It can handle non-local redirects,
It saves the return address and execution environment, similar to setjmp and longjump in C, but it saves
For more information:
The example of Cao cited by axgle is very vivid. Let's take a look:
From [http://www.javaeye.com/topic/44271]
CAOCAO is hailed as "the best man in ancient times" because it is the phrase "Cao, Cao" Famous saying .
In Ruby, Cao is called callcc.
Ruby code
Callcc {| Caocao |
For say in ["Cao", "Zhuge Liang", "Zhou Yu"]
CAOCAO. Call if say = "Cao"
Puts say # No output, because Cao has already flown out
End
} # "Cao" flew here (jumping out of the callcc block, followed by the block and continuing to execute the following Ruby code)
Puts ""
CAOCAO in callcc is a "Continuation" object. This object only has such a method called "call.
After Caocao. Call is executed, Caocao will fly to the block of callcc and let Ruby continue to execute the following code.
The above is an example of "Flying" from the block to the block outside. The following is an example of "Flying" from the back of the Code to the front of the Code provided by programming Ruby:
Ruby code
Arr = ["Freddie", "Herbie", "Ron", "Max", "ringo"]
Callcc {| $ CC |} # If the $ cc. Call below is executed, it will fly back here (after the callcc block ).
Puts (Message = arr. Shift)
$ Cc. Call unless message = ~ /Max/
Most examples are from <the Ruby way>