Learning notes for Ruby built-in classes

Source: Internet
Author: User
Tags add numbers class definition comparable comparison instance method mixed regular expression

Ruby's Literal builder

Most of Ruby's built-in classes can be instantiated using new:

str = string.new
arr = array.new
Some classes cannot be instantiated using new, such as the Integer class. Some built-in classes can use a literal constructor, or you don't need to use new, and you can use a special form to create an instance of a class.

Literal constructors for built-in classes

String: Using quotes,--"new string", ' new string '
Symbol: Colon in front,--:symbol,: "Symbol with spaces"
Array: square brackets,--[1,2,3]
Hash: curly braces,--{"New York" => "NY", "Oregon" => "OR"}
Range: Two or three dots,--0..9 or 0...10
Regexp: Slash,--/([a-z]+)/
Proc (LAMBDA): Horizontal line, arrow, bracket, curly brace ——-> (x,y) {x * y}
Sugar-coated grammar

Grammatical sugars (syntactic Sugar). The method call is in this form: Object.Method (args), but Ruby provides some sugar-coated syntax to make the method call more beautiful:

x = 1 + 2
The above is equivalent to:

x = 1.+ (2)
Define the operator by defining the method

If you define a + method in a class, the object of your class can use the icing syntax of addition. Note that the operator is also a method, and this method is used only as an operator to make it look better.

Using + is a convention, Ruby itself does not know the meaning of + is addition. You can define your own + method of not addition:

obj = object.new
def obj.+ (Other_obj)
"Do you want to add something?" "
End
Puts obj + 100
The + on the puts is called the + method above obj, and integer 100 is its unique parameter. In fact, the + method on obj is not the meaning of addition, but simply the output of a string.

On the operator icing is the fast icing: x = 1 is x = x + 1. The following bank account class has + and-method:

Class Account
Attr_accessor:balance

def initialize (amount=0)
Self.balance = Amount
End

def + (x)
Self.balance = X
End

Def-(x)
Self.balance-= X
End

def to_s
balance.to_s
End
End

ACC = account.new (20)
ACC-= 5
Puts ACC
The result of the above output is 15. After defining-this instance method, we can use the-= this shortcut.

Custom unary Operators

+ and-is a unary operator, in its own class or object you can specify the behavior of +obj and-obj these expressions, you can define methods +@ and-@.

For example, you want to redefine the behavior of + and-in a class called Banner, making them mean to turn strings into uppercase letters or lowercase letters:

Class Banner
def initialize (text)
@text = text
End

def to_s
@text
End

def +@
@text. upcase
End

def-@
@text. downcase
End
End
And then experiment again:

Banner = Banner.new ("Eat at David ' s!")
Puts banner # output: Eat at David ' s!
Puts +banner # output: EAT at DAVID ' S!
Puts-banner # output: Eat at David ' s!
5:30 * * *

7:22 * *

You can also define! operator, define one! method on the line, you will have a unary operator after completion! , there is also a not:

Class Banner
Def!
Reverse
End
End
Experiment again:

Puts!banner # output:!s ' Divad ta TaE
Puts (not banner) # output:!s ' Divad ta TaE
! Method

September 11, 2016 9:41 * * *

Ruby's method can be used! The end of the number, indicating "danger". For example, two ways to do the same thing, one of them has a bit of side effects, you can say that it is a bit dangerous, then you can let these two methods call a name, but the side-effect or a bit dangerous method of the last name can add one! The end of the number, such as (UpCase and upcase!).

It's Ruby's custom, or the Convention,! The number itself has no particular meaning within Ruby. But by convention, a method with an exclamation mark means that it is a dangerous method. What is dangerous is actually defined by the person who wrote this method. For example, in Ruby's built-in class, take! Number method, it may change its receiver without the exclamation mark version. But that's not always the case, like: exit/exit!,sub/sub!.

You can also think of danger as a warning, or a note! Most of the methods with the exclamation mark have a version without the bar number, which appears in pairs.

Destructive

Some bands of Ruby core band! The end of the number method is destructive, that is, they change the object that calls it. For example UpCase this method, it will return a new letter string of uppercase letters, but upcase! Method will directly change the original string.

Do an experiment:

>> str = ' Hello '
=> "Hello"
>> Str.upcase
=> "HELLO"
>> Str
=> "Hello"
>> str.upcase!
=> "HELLO"
>> Str
=> "HELLO"
There are many such methods in Ruby's core, such as sort/sort!,strip/strip!,reverse/reverse!. The method without the exclamation mark returns the new object, and the method with the exclamation mark changes the original object directly. You have to pay attention to whether the calling method will change its receiver. The method of returning the new object consumes more resources than the method that modifies the original object.

On the other hand, you should also note that modifying the original object may affect other places in the program, such as the possibility of using the original object that has not been modified.

Destruction and Danger

Destruction is not the same as danger, and some destructive methods may not take it! Resolution Ruby itself doesn't care if it's in the way! Number, as long as it is the method it will be executed. This one! The number is a way of communicating between the author and the user of the method. It is a custom that an experienced person will know what it means at a glance.

Want to use the belt! Number method, the method must have a corresponding to it does not take! Version of the number. The two ways to do things basically the same, is to take! The method may have some side effects, such as returning a different value, or having some other heel! The method of the number of different behavior.

Don't you think the method is a bit dangerous in some ways and is used in the name of the method! Resolution Because any method itself is not dangerous. Only in some relative cases, one method has two names, one with an exclamation mark, one without an exclamation mark, with an exclamation point means that this method may have some side effects.

For example, a way to save a file, not because it can save the file to disk, you call it save! , just call it save. Unless you need another method to save the file without backing up the original file (assuming the Save method can back up the original file), you can call this method save!.

Note that not all destructive methods are used! The end of the number. No one is forced to use the name of the method! No, it's just a convention.

To_*

11:54 * * *

Ruby has some methods that start with to_, and they can transform objects. such as to_s (converted to strings), To_sym (converted to symbols), to_a (convert array), to_i (Convert integer), to_f (convert floating-point decimal).

to_s: Converting strings

Do an experiment:

>> "Hello". to_s
=> "Hello"
Try again:

>> ["One", "two", "three", 4, 5, 6].to_s
=> "[one\", \ "two\", \ "Three\", 4, 5, 6] "
Try again:

>> Object.new.to_s
=> "#<object:0x007fbde88267e0>"
And do an experiment:

>> obj = object.new
=> #<object:0x007fbde882d9a0>
>> puts obj
#<object:0x007fbde882d9a0>
=> Nil
>> def obj.to_s
>> "I ' m an object!"
>> End
=>: to_s
>> puts obj
I ' m an object!
=> Nil
String interpolation also uses the to_s:

>> "My Object says: #{obj}"
=> "My Object says:i ' m a object!"
Take a look at the Inspect method:

>> Object.new.inspect
=> "#<object:0x007fbde8963e78>"
IRB automatically invokes the inspect method on the output value:

>> object.new
=> #<object:0x007fbde8960ed0>
>> ' abc '
=> "ABC"
>> [1,2,3]
=> [1, 2, 3]
>> a regular expression/
=>/A regular expression/
You can define inspect in your class:

Class Person
Def initialize (name)
@name = Name
End

def inspect
@name
End
End

David = Person.new (' David ')
Puts David.inspect
The result of the output is David.

Then use the display:

>> ' Hello '. Display
Hello=> Nil
To_a: Converting arrays

[1,2,3,4,5]
What's in the square brackets is a list, not an array, and then it's an array with square brackets.

>> array = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
>> [*array]
=> [1, 2, 3, 4, 5]
If you do not use the * number:

>> [Array]
=> [[1, 2, 3, 4, 5]]
Parameters:

def combine_names (first_name, last_name)
First_Name + "" + last_name
End

names = ["David", "Black"]
Puts Combine_names (*names)
The output is: David black. If you do not use the * number, the value of your argument will be an array.

To_i and To_f

Ruby does not automatically convert strings to numbers or converts numbers to strings.

Try this:

>> 1 + "2"
Will prompt:

Typeerror:string can ' t be coerced into fixnum
From (IRB): 25:in ' + '
From (IRB): 25
From/usr/local/bin/irb:11:in ' <main> '
Because Ruby doesn't know what it means to add numbers to a string.

And do an experiment:

print ' Enter a number: '
n = Gets.chomp
Puts N * 100
The result is that what you enter will be output 100 times. To treat the input as a number, you have to:

n = gets.to_i
Try again:

>> ' Hello '. to_i
=> 0
To keep the number part of a string:

>> ' 123hello '. to_i
=> 123
The part of the number to be kept in front, in the back is not possible:

>> ' hello123 '. to_i
=> 0
The behavior of the To_f method is similar to that of To_i.

Strict conversion

Use Integer and Float.

>> ' 123abc '. to_i
=> 123
>> Integer (' 123abc ')
Argumenterror:invalid value for Integer (): "123abc"
From (IRB): 34:in ' Integer '
From (IRB): 34
From/usr/local/bin/irb:11:in ' <main> '
>> Float (' 3 ')
=> 3.0
>> Float ('-3 ')
=>-3.0
>> Float (' -3xyz ')
Argumenterror:invalid value for Float (): " -3XYZ"
From (IRB): 37:in ' Float '
From (IRB): 37
From/usr/local/bin/irb:11:in ' <main> '
Role Play to_*

>> ' Hello ' + ' there '
=> "Hello there"
>> ' Hello ' + 10
Typeerror:no implicit conversion of fixnum into String
From (IRB): 40:in ' + '
From (IRB): 40
From/usr/local/bin/irb:11:in ' <main> '
Class Person
Attr_accessor:name
def TO_STR
Name
End
End
If you create a person object, let it add a string, to_str

>> David = Person.new
=> #<person:0x007fbde8a498d8>
>> david.name = ' David '
=> "David"
>> puts ' David is named ' + David + '. '
David is named David.
=> Nil
To_ary

Class Person
Attr_accessor:name,: Age, "email"
def to_ary
[Name, age, email]
End
End
Try the following:

>> David = Person.new
=> #<person:0x007fbde89fa2b0>
>> david.name = "David"
=> "David"
>> David.age = 55
=> 55
>> david.email = "David@wherever"
=> "David@wherever"
>> array = []
=> []
>> Array.concat (David)
=> ["David", "David@wherever"]
>> P Array
["David", "David@wherever"]
=> ["David", "David@wherever"]
Boolean state, Boolean object, nil

Each expression in Ruby computes an object with a Boolean value, True or FALSE, inside each object. True and false are objects themselves. In many cases, where you want true or false values, such as if statements, or two numbers, you don't have to deal with these particular objects directly, in which case you can think of the true or false as a state, not an object.

True and false as status

The expression in Ruby is either true or false. You can use the IF statement to verify that the expression is true or false.

Do some experiments:

if (class MyClass; end)
Puts ' Blank object is True '
Else
Puts ' blank object is False '
End

if (class MyClass; 1; end)
Puts ' class definition has a number 1 is true '
Else
Puts ' class definition has a number 1 is false '
End

if (def m; return false; end)
Puts ' method definition is true '
Else
Puts ' method definition is false '
End

If ' string '
Puts ' string is true '
Else
Puts ' string is False '
End

If > 50
Puts ' 100 greater than 50 '
Else
Puts ' 100 not greater than 50 '
End
The result will be:

The blank object is False
There is a number 1 in the class definition that is True
Method definition is True
String is True
100 Greater than 50
Try again to see what the expression returns:

>> class MyClass; End
=> Nil
>> class MyClass; 1; End
=> 1
>> def m; return flase; End
=>: M
>> ' String '
=> "string"
>> > 50
=> true
> 50 Returns True for this object.

is true and false as an object

True and false are special objects, which are unique instances of the Trueclass and Falseclass classes.

Do an experiment:

>> puts True.class
Trueclass
=> Nil
>> puts False.class
Falseclass
=> Nil
True and false are keywords, so you can't use them in the name of a variable or method.

>> A = True
=> true
>> A = 1 unless a
=> Nil
>> A
=> true
>> B = A
=> true
Sometimes you will see the use of true or false as a parameter to the method. For example, if you want a class to display all of its instance methods, but do not want to display an instance method in an ancestor class, you can do this:

>> String.instance_methods (False)
Jiè

Nil is the only instance of Nilclass. The Boolean value of the nil is false. What Nil says is that there is nothing.

Do an experiment:

Puts @x
Puts a nonexistent instance variable, the output is nil. Nil is also the default value for elements that do not exist, such as you create an array with three items in it, and when you access the Nineth item in the array, the value is nil. Try this:

>> [' One ', ' two ', ' three '][9]
=> Nil
Nil said that there is no and there is no. However, the nil itself is present, and it can be invoked as other objects in response to the method:

>> nil.to_s
=> ""
>> nil.to_i
=> 0
>> nil.object_id
=> 8
Nil and false are the only two objects in Ruby that have a Boolean value of false.

2:53 * * *

Compare two objects

3:28 * * *

Ruby objects can compare whether they are equal to other objects.

Equality test

Do some experiments:

>> A = Object.new
=> #<object:0x007fbde89294a8>
>> B = object.new
=> #<object:0x007fbde89099c8>
>> A = = a
=> true
>> A = = b
=> false
>> a!= b
=> true
>> a.eql? (a)
=> true
>> a.eql? (b)
=> false
>> a.equal? (a)
=> true
>> a.equal? (b)
=> false
In the above experiment, we used three kinds of equality test methods, ==,eql?,equal? , they give the same result. A is equal to a, and a is not equal to B.

Can you redefine the = = and EQL in your own class? Method. Usually keep a equal? method, you can use it to compare two objects to represent the same object. For example, in the String category to redefine the = = and eql? Method:

>> string1 = ' text '
=> "Text"
>> string2 = ' text '
=> "Text"
>> string1 = = string2
=> true
>> string1.eql? (string2)
=> true
>> string1.equal? (string2)
=> false
Comparable module

The most common redefinition of the equality test method is = =. It's a test method of equality. A member of the family, but also the members of the comparative method clan, ==,!==,>,<,>=,<=.

If you need to have all of these comparison methods for objects of this class of MyClass, you only need to:

Mix the comparable module into the MyClass.
Define a comparison method using the <=> name in MyClass.
<=> comparison methods are sometimes called spaceship operators or spacecraft methods. In this method you can define less than, equal to, greater than what exactly is meant. When you're done, Ruby will provide you with a corresponding comparison method.

For example, you have a bid class, the name is Bid, you can track incoming bids, you want to have some comparison features that can compare two Bid objects based on estimate properties. The simple operators of >,< can be used when comparing.

Class Bid
Include comparable
Attr_accessor:estimate
def <=> (Other_bid)
If Self.estimate < other_bid.estimate
-1
elsif self.estimate > Other_bid.estimate
1
Else
0
End
End
End
Simple, you can do this;

def <=> (Other_bid)
Self.estimate <=> Other_bid.estimate
End
Experiment:

>> BID1 = bid.new
=> #<bid:0x007fbde8960778>
>> Bid2 = bid.new
=> #<bid:0x007fbde8959928>
>> bid1.estimate = 100
=> 100
>> bid2.estimate = 105
=> 105
>> Bid1 < Bid2
=> true
Ability to check objects

Inspection and reflection are some of the things that make a Ruby object about itself in its lifecycle.

Ways to List objects

You want to know what information an object can understand, that is, what method can be invoked on it, and try:

>> ' I'm a String object '. Methods
You'll see a lot of ways in which the order can be sorted:

>> ' I'm a String object '. Methods.sort
The methods method can also be used on module objects and class objects:

>> String.methods.sort
The method in the list is the method of the object such as String.

By defining an independent method on a string object and then looking at the list of methods for that object, you will find the independent method defined on this object:

>> str = ' A plain old string '
=> "A plain old string"
>> def str.shout
>> self.upcase + "!!!"
>> End
=>: Shout
>> Str.shout
=> "A PLAIN old STRING!!!"
>> Str.methods.sort
You can also display independent methods of objects individually:

>> Str.singleton_methods
=> [: Shout]
In a class, the module is mixed, the method in the module, the instance object of the class can be called, and then an experiment is done:

>> str = ' Another plain old string. '
=> "Another plain old string."
>> Module Stringextras
>> def shout
>> self.upcase + '!!! '
>> End
>> End
=>: Shout
>> class String
>> include Stringextras
>> End
=> String
>> str.methods.include? (: Shout)
=> true
A string object is created, a module is created, and the module is mixed into the string class to see if the first created string object contains the shout method defined in the module: Returns TRUE.

Query classes and Module objects

When executing String.methods.sort in IRB, you will find a Instance_methods method that tells us the instance method that the instance of the String class can use:

>> String.instance_methods.sort
You can also ask the module:

>> Enumerable.instance_methods.sort
Filter and select a list of methods

Sometimes you want to know the instance method defined above for a particular class, and do not want to include the method defined by the ancestor of this class, you can do this:

String.instance_methods (false). Sort
What you see is just the instance method defined on the String class. There are several ways to list methods:

Obj.private_methods
Obj.public_methods
Obj.protected_methods
Obj.singleton_methods
Class and the instance method on the module:

Myclass.private_instance_methods
Myclass.protected_instance_methods
Myclass.public_instance_methods
Public_instance_methods with Instance_methods is a meaning.

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.