Ruby Learning Notes Ruby Object

Source: Internet
Author: User
Tags error handling require ticket

Most Ruby programs, their design, logic, and action, are all centered around objects. The main task of writing a Ruby program is to create objects and then give them the ability to perform actions.

Ruby is an OOP language, an object-oriented language in which you perform calculations, data processing, input, and output by creating objects and then letting the object perform the specified action. Objects (object) in the real world, is a thing. An apple is an object, and a table is an object.

Each object is an instance of a particular class (instance), and the behavior of the object is largely determined by the method defined above the class to which they belong.
When you want to do something, such as calculation, output, data comparison, you are letting an object do it. For example, if you want to ask if a is equal to B, you are asking whether a is thinking that it is equal to B. If you want to know if a student is in a teacher's class, you can ask the student, "Are you a student of this teacher".

To write a Ruby program, most of the work is to create objects so that each object plays a role, and each object can perform the actions associated with that role.

Create a Generic Object

Class is a way of bundling and tagging behavior, which makes it easier to create multiple objects that have similar behavior. In Ruby, each object is likely to learn some behavior (method), which may not be in their class. The concept of a class applies to the concept of objects, not the other way around, so let's look at the objects first.

Create a generic object that does not represent a specific thing:

obj = object.new
The above is the creation of an object, which is given to the variable obj, which you can use to handle the newly created object.

>> obj = object.new
=> #<object:0x007fb839154e80>
All Ruby objects are inherently capable of having some way to execute. We can also teach the object what you want it to do.

Defining the behavior of an object

If you want an object to speak, you have to let it speak first, and you have to teach it to speak before you let it speak. is to define the method in the object, you can use the keyword def to define the method.

def Obj.talk
Puts ' I'm an object '
Puts ' Are you? ' '
End
Sending information to an object

Let obj this object be able to speak, execute:

Obj.talk
will return:

I'm an object.
Are you?
Object obj can now understand or respond to the talk message sent to it, and the object will execute this method if there is a method corresponding to this information on the object.

The point (.) is an operator that sends the message, and the information to the right of the point is sent to the object to the left of the point.
The receiving and receiving of information is usually an object that is represented by a variable, or it can be a literal object, such as a string with quotes.
Most of the information sent is the name of the method, such as the previous talk. The object attempts to run the method that corresponds to the information, triggering error handling (error-handling) If the method does not exist.
A method with parameters

When calling a method, you can provide one or more parameter values for the method. When defining a method, a parameter is a variable of a list in parentheses that appears to the right of the method name, and can be either mandatory or optional. When calling methods, you can provide values for these variables.

When you define a method, those variables that are listed are the formal parameters (formal parameters) of the method. When you invoke a method, the specific values you provide for these variables are the arguments (actual parameters) of the method. In general, we can use arguments to represent the parameters of the method, including formal parameters and actual parameters. Chinese can be directly called parameters.

For example, a method of Celsius temperature transfer to Fahrenheit:

def obj.c2f (c)
c * 9.0/5 + 32
End
The above method supports a parameter C, which provides a value for this parameter when invoking this method:

Puts obj.c2f (100)
The result:

212.0
The parentheses are optional when defining and invoking a method.

def obj.c2f C
OBJ.C2F 100
The return value of the method

Ruby's expressions all have a value, and the following are expressions and their values.

>> 2 + 2
=> 4
>> ' Hello '
=> "Hello"
>> ' Hello ' + ' there '
=> "Hello there"
>> C = 100
=> 100
>> c * 9/5 + 32
=> 212
>> obj.c2f (100)
=> 212.0
503cf7f1-4c64-4abc-98c5-2c9e5886bbe2

The invocation of each method is an expression. When you call a method, the method calculates something, and the result is the value returned by the method (return value).

In defining the method and time, you can also use the return keyword to go back to the value:

def obj.c2f (c)
Return c * 9.0/5 + 32
End
The above example is the same as the method we defined earlier, plus the return is clearer, and returns allow multiple values to be returned, like return a,b,c, where the list of returned values is automatically placed in an array. The call to each method returns something, regardless of the use of return. Even a method of a blank body, it will return a nil.

Create an object that represents the ticket

A ticket (ticket) can provide some data about itself, such as the time, location, name of the show, who the performer is, which seat, how much money, and so on.

01/02/03
Town Hall
Author ' s Reading
Mark Twain
Second balcony, Row J, seat 12
$5.50
Creating objects

Creating an object makes it easy to get the information above.

Ticket = Object.new
After having ticket this object, define some methods in it:

def ticket.date
' 01/02/03 '
End

def ticket.venue
' Town Hall '
End

def ticket.event
' Author ' s reading '
End

def Ticket.performer
' Mark Twain '
End

def ticket.seat
' Second balcony, row J, Seat 12 '
End

def Ticket.price
5.50
End
Now the ticket object knows something about himself.

Query Object

To get the Ticket object time, you can perform ticket.date, obtain a seat, and perform ticket.seat.

string interpolation

String interpolation is the insertion of a value in a string. In the form of something #{represents a value}, such as #{ticket.event}.

Puts "This ticket are for: #{ticket.event}, at #{ticket.venue}." +
"The performer is #{ticket.performer}." +
"The seat is #{ticket.seat}," +
"And it costs $#{"%.2f. "% Ticket.price}"
Boolean value in the method

If a ticket has been sold, one way is to add an available state to it:

def ticket.availability_status
"Sold"
End
Another way is to ask if it is available, it will return TRUE or false:

def ticket.available?
False
End
True and False are objects in Ruby, and they can be used to represent true or false in a method. Notice available? Here's a question mark, which calculates true or false, so it's a bit like asking a question when using this method:

If ticket.available?
Puts "You ' re in luck!"
Else
Puts "Sorry--that seat has been sold."
End
Every expression in Ruby gets an object that has a value that is true in almost all Ruby objects, and that object is a true or false one. Only false is false and the value in the Nil object is true.

Abbc0d70-3a82-47df-a2e0-50ae1cd5abc6

>> if ' abc '
>> puts ' string is true in Ruby '
>> End
(IRB): 105:warning:string literal in condition
In Ruby, the string is true.
=> Nil
>> if 123
>> puts ' number is true '
>> End
Number is True
=> Nil
>> if 0
>> puts ' 0 is true, noting that 0 is not true in some languages
>> End
0 is also true, note that 0 is not true in some languages
=> Nil
>> if 1 = 2
>> puts ' 1 does not equal 2, so it will not display this string '
>> End
=> Nil
The natural behavior of the object

September 5, 2016 1:11 * * * *

After an object exists, it has some innate behaviors, look at these innate behaviors, and perform the following:

>> puts Object.new.methods.sort
!
!=
!~
<=>
==
===
=~
__id__
__send__
Class
Clone
Define_singleton_method
Display
Dup
Enum_for
Eql?
Equal?
Extend
Freeze
Frozen?
Hash
Inspect
Instance_eval
Instance_exec
Instance_of?
Instance_variable_defined?
Instance_variable_get
Instance_variable_set
Instance_variables
Is_a?
itself
Kind_of?
Method
Methods
Nil?
object_id
Private_methods
Protected_methods
Public_method
Public_methods
Public_send
Remove_instance_variable
Respond_to?
Send
Singleton_class
Singleton_method
Singleton_methods
Taint
Tainted?
Tap
To_enum
to_s
Trust
Untaint
Untrust
Untrusted?
=> Nil
ID of the object

Each object has an ID, which is in the object_id, such as:

>> ' Hello '. object_id
=> 70214603696960
Let's do one more test:

>> A = Object.new
=> #<object:0x007fb83904f8c8>
>> B = A
=> #<object:0x007fb83904f8c8>
>> a.object_id
=> 70214603668580
>> b.object_id
=> 70214603668580
Let's do one more test:

>> string_1 = ' Hello '
=> "Hello"
>> string_2 = ' Hello '
=> "Hello"
>> string_1.object_id
=> 70214603633100
>> string_2.object_id
=> 70214603619360
The strings represented by string_1 and string_2 are hello, but their object_id are not the same.

Query whether the object can do anything

Try it first:

>> obj = object.new
=> #<object:0x007fb8390262e8>
>> Obj.talk
Nomethoderror:undefined method ' Talk ' for #<object:0x007fb8390262e8>
From (IRB): 128
From/usr/local/bin/irb:11:in ' <main> '
Create a new object and try to send it talk this message, Ruby will prompt talk This method has not been defined. So try again:

obj = object.new

If obj.respond_to? ("Talk")
Obj.talk
Else
Puts "Sorry, the object doesn ' t understand the ' talk ' message."
End
Create an object that uses the object's respond_to? , ask if it can talk. Respond_to? is the innate ability of an object to query whether an object can respond to certain information.

Send information using the Send method

The ticket object that you created before, assuming that you want to return the corresponding information about the object based on what the user has entered, the code looks like this:

Print "Information desired:"
Request = Gets.chomp
And then you can make a judgment:

If request = = "Venue"
Puts Ticket.venue
elsif request = = "Performer"
Puts Ticket.performer
...
The above method is a bit long, you can also do this:

If ticket.respond_to? (Request)
Puts Ticket.send (request)
Else
Puts "No such information"
End
With respond_to? Ask if the input is not, that is, whether the object can respond to this information, if it is, send this method of sending this information, that is, let the object to carry out the corresponding method.

Parameter of the method

A method in Ruby can contain 0 or more parameters. The number of parameters can also be variable.

Must be with optional

Let's do an experiment:

obj = object.new

def obj.one_arg (x)
Puts "I require one and only one argument!"
End

Obj.one_arg (1,2,3)
The result will be:

Argumenterror:wrong Number of arguments (3 for 1)
It means that the number of parameters is wrong, there should be only one parameter, you have given three.

To add multiple parameters to a method, you can use the * number, like this:

def Obj.multi_args (*x)
Puts "I can take zero or more arguments!"
End
*x This argument means that you can add any number of arguments when you call this method. The value of this parameter will be an array.

Let's look at an example of a mixed-use parameter:

def two_or_more (A,b,*c)
Puts "I require two or more arguments!"
Puts "and sure enough, I got:"
p A, B, c
End
If you call the above method like this: Two_or_more (1,2,3,4,5), you get something like this:

I require two or more arguments!
And sure enough, I got:
1
2
[3, 4, 5]
The p in the aspect is the output of the object, and the output is the value of the parameters passed to the A,b,c in the method. The argument passed when the method is invoked is 1,2,3,4,5, so that the value of the A parameter should be 1, the value of the B parameter is 2, and the rest is the value of the C parameter, which is an array containing the 3,4,5.

Default values for parameters

When you define a method, you can set the default value for the parameter, and if you call the method without setting the value of the parameter, the default value of that is used.

def Default_args (a,b,c=1)
Puts "Values of variables:", a,b,c
End
If you call the above method like this:

Default_args (3,2)
The results obtained are:

Values of variables:
3
2
1
When the method is invoked we do not pass a value to the C parameter, so we use its default value, which is 1.

Order of parameters

Let's take a look at an example:

def Mixed_args (A,b,*c,d)
Puts "Arguments:"
P A,b,c,d
End

Mixed_args (1,2,3,4,5)
The result of the call method return is like this:

Arguments:
1
2
[3, 4]
5
*c is a sponge parameter, it has a lower priority, so if you call this method:

Mixed_args (1,2,3)
The result returned would be:

1
2
[]
3
The following is a more detailed parameter example:

Have to
def m (ABC)
M (1,2,3)
A = 1, b = 2, c = 3

Optional
def m (*a)
M (1,2,3)
A = [1,2,3]

Default
def m (a=1)
M
A = 1
M (2)
A = 2

Must/optional
def m (A, *b)
M (1)
A = 1, b = []

Must/Default
def m (a,b=1)
M (2)
A = 2, B = 1
M (2,3)
A = 2, B = 3

Default/Optional
def m (A=1, *b)
M
A = 1, b = []
M (2)
A = 2, b = []

Must/default/optional
def m (a,b=2,*c)
M (1)
A = 1, b = 2, c = []
M (1,3)
A = 1, b = 3, c = []
M (1,3,5,7)
A = 1, b = 3, c = [5,7]

Must/default/optional/must
def m (a,b=2,*c,d)
M (1,3)
A = 1, b = 2, c = [], d = 3
M (1,3,5)
A = 1, b = 3, c = [], d = 5
M (1,3,5,7)
A = 1, b = 3, c = [5], d = 7
M (1,3,5,7,9)
A = 1, b = 3, c = [5, 7], d = 9

2:15 * * * *

Local Variables and variable assignments

2:15 * * * *

Local variables can begin with lowercase letters or underscores, or they can contain numbers, and the following are qualified local variable names:

X
_x
Name
First_Name
Plan9
user_id
_
A local variable means that its scope is limited, and each local variable will only work in one place in the program. For example, two local variables of the same name may be included in different parts of the program.

The common scope of action is in the definition of a method, look at an example:

def Say_goodby
x = ' Goodbye '
Puts X
End

def Start_here
x = ' Hello '
Puts X
Say_goodby
Puts ' Let us check whether X remained the same: '
Puts X
End

Start_here
The results of the execution should be:

Hello
Goodbye
Let us check whether X remained the same:
Hello
The first line outputs the value of the x variable defined in Start_here, that is, hello, the second line executes the say_goodby in the Start_here, outputs the value of the X defined in the method, and the value of the X in the Start_here, which is still Is the value of the X that is defined internally in this method.

Variables, objects, references

Try it first:

str = ' Hello '
Now the variable of STR is the string hello.

Try again:

str = ' Hello '
ABC = str
Puts ABC
Str says Hello, assigning the value of STR to ABC, so when you output ABC, the result is hello.

Try again:

str = "Hello"
ABC = str
Str.replace ("Goodbye")
Puts Str
Puts ABC
def Say_goodbye
str = "Hello"
ABC = str
Str.replace ("Goodbye")
Puts Str
Puts ABC
End

Say_goodbye
The result of the output is:

Goodbye
Goodbye
The first goodbye is STR and the second is ABC, but we only replaced STR, so why is the value of ABC replaced?

Reference

In Ruby, in most cases the variable itself does not contain the value of the object, and the str above does not include the word hello, which contains only a reference to the string object.

In an assignment, the left is a variable, and the right is an object, and the variable receives a reference to the object. If you assign a variable to another variable, such as ABC = str, the variable on the left copies a reference to the right variable, which means that the two variables refer to the same object.

Str.replace ("Goodbye")
Replacing the string referenced by str with goodbye, variable ABC refers to the same string object, so the substitution action on STR also affects ABC, which means that the contents of the string become goodbye.

Something not to be quoted

In Ruby, some objects are stored in variables as immediate values. such as integers, symbols (symbol, looks like this, a colon in front of the string), and True,false,nil. When you assign these values to a variable, the variable saves the value itself, not a reference to them. Ruby automatically determines whether to use references.

Any object that represents an immediate value is always the only object, regardless of how many variables it assigns. For example, there is only one 100 object, only one False object.

Ruby's object must have one or more references to it, and if there is no reference, it frees up the memory occupied by the object.

If you have two or more variables pointing to the same object, you can use either of these variables to send information to the object they represent.

Assigning and reassigning a reference in a variable

Every time a variable is allocated, it clears the object that is previously represented by the variable. To try:

str = "Hello"
ABC = str
str = "Goodbye"
Puts Str
Puts ABC
The output of this return is:

Goodbey
Hello
Reference and Method parameters

To segment code:

def change_string (str)
Str.replace ("New content")
End
Then create a string and send it to change_string:

s = "Original content"
Change_string (s)
Check again:

Puts S
The result will be:

New content
If you don't want to change that string, you can try this:

s = "Original string content!"
Change_string (S.dup)
Puts S
The DUP method copies a new object. You can also do this:

s = "Original content"
S.freeze
Change_string (s)
Puts S
Local variables and things that look like them.

Ruby sees these things: S,ticket,puts,user_name, which will interpret them as one of the following three things:

Native variables: local variable
Key words: keyword
Method calls:
The keyword is a reserved word for Ruby and you can't use it as a variable name. Like Def,if, these are all keywords. Similar to local variables, method calls are plain text, and if the method has arguments, it is easy to know that they are not a variable after parentheses. If the method is called without parentheses, Ruby will know what it is.

Ruby is this way of judging identifiers:

If the identifier is a keyword, it is a keyword.
If an equal sign appears to the right of the identifier, it is a local variable.
The other case identifier would be a call to a 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.