Programming Ruby Reading Notes

Source: Internet
Author: User
Tags naming convention

  • In Ruby, you can call constructor to create an object.

Song1 = song. New ("Ruby ")

  • Ruby rarely processes single quotes. Except for a few exceptions, the literal content entered into the string constitutes the value of this string.

Ruby handles more double quotation mark string games. First, it looks for the sequence starting with a backslash and replaces them with binary values. Second, the expression in the string is interpolated, And the # {expression} sequence is replaced by the value of the "expression.

  • $ Greeting = "hello" # $ greeting is a global variable
  • @ Name = "prodence" # @ name is the instance variable
  • Ruby uses a naming convention to differentiate the purpose of a name: the first character of the name shows how the name is used. Local variables, method parameters, and method names must start with lowercase letters or underscores. Global variables all have a $ prefix. instance variables start with the @ symbol and class variables start with the @ symbol. The class name, Module name, and constant must start with an uppercase letter.
  • In many languages, the concept of nil (or null) is "no object". In Ruby, this is different: Nil is an object, just like other objects, but it is used to indicate that there is nothing.
  • A = % W {ant bee cat dog} is equivalent to the following expression:
  • A = ['ant', 'bee ', 'cat', 'dog']
  • A regular expression is only a method that specifies the character pattern. This character pattern is matched in the string. In Ruby, regular expressions are usually created by writing a pattern between the slash (/pattern.
  • Block:

Def call_block

Puts "Start of method"

Yield

Yield

Puts "End of method"

End

Call_block {puts "in the block "}

 

Result:

Start of Method

In the block

In the block

End of Method

 

Use block to implement the iterator: The iterator is a method for collecting elements such as continuous return from an array.

Animals = % W (ANT bee cat dog elk)

Animals. Each {| animal | puts animal}

 

Result:

Ant

Bee

Cat

Dog

Elk

  • Class

Class song

Def initialize (name, artist, duration)

@ Name = Name

@ Artist = artist

@ Duration = duration

End

End

Song = song. New ("bicyclops", "fleck", 260)

Puts song. Inspect

 

Result:

# <Song: 0x00000002eca6d8 @ name = "bicyclops", @ artist = "fleck", @ duration = 260>

The inspect method (which can be sent to any object) formats the Object ID and instance variables by default.

 

  • The external visible part of an object is called its attribute)

Class karaokesong <song

Def initialize (name, artist, duration, lyrics)

Super (name, artist, duration)

@ Lyrics = lyrics

End

Def to_s

"KS: # {@ name} -- # {@ artist} (# {@ duration}) {#{@ lyrics }}"

End

Attr_reader: name,: artist,: duration,: lyrics # attributs setting method 2

Def name # Attribute setting method 1

@ Name

End

Def artist

@ Artist

End

End

 

Song = karaokesong. New ("bicyclops", "fleck", 260, "and now, ...")

Puts song. Artist

 

  • When super is called without parameters, Ruby sends a message to the parent class of the current object, requiring it to call the method with the same name in the subclass.
  • Object instance method
  • Writable attributes:

Method 1: Create a method whose name ends with an equal sign

Method 2: attr_writer

  • Virtual attributes virtual attributes

 

In the preceding example, a virtual instance variable is created using the attribute method. For the external world, duration_in_minutes is like other attributes. However, it does not have corresponding instance variables internally.

 

  • Attributes, instance variables, and methods

Attribute is a method. In some cases, the attribute simply returns the value of the instance variable. In some cases, the property returns the calculated result. In addition, some methods whose names end with equal signs are used to update the object state.

When designing a class, it determines its internal status and its external manifestation. The internal status is saved in the instance variable. External States exposed by methods are called attributes. Class can execute other actions, is the general method.

 

  • Class variables: class variables start with two @ characters. Unlike global variables and instance variables, class variables must be initialized before use. Generally, Initialization is a simple value assignment in the class definition.

 

  • Class methods are not bound to any specific object methods.

The new method creates a new class object, but the new method itself is not associated with a specific object.

Class methods and instance methods are distinguished by their definitions: Class names and a period are placed before the method names to define class methods.

 

 

  • Access Control
  1. The public (public) method can be called by anyone without restrictions on access control. The default method is public (except initialize, which is private)
  2. The protected (Protection) method can only be called by the class that defines the method or its subclass object. Accessible to all families
  3. A private (private) method cannot be called by a specified receiver. Its receiver can only be self. This means that rare methods can only be called in the context of the current object; you cannot call private methods of another object

 

 

In addition, you can pass the method name as the parameter list into the access control function to set their access level.

  • Variable

Is a variable an object? In Ruby, the answer is "no '. Variables are only references to objects. Objects float somewhere in a large pool (most of the time in a heap) and point to them by variables.

You can use the string DUP method to avoid alias creation. It creates a new String object with the same content.

You can freeze an object to prevent others from making changes to it. Trying to change a frozen object, Ruby will cause a typeerror exception

  • Container (continuers): refers to an object that contains one or more object references.

The array class contains a group of object references. Each object reference occupies a position in the array and is identified by a non-negative integer index.

 

Arrays are indexed using the [] operator. Like most operators in ruby, it is actually a method (an instance method of the array class), so it can be overloaded by the quilt class. If you use a non-negative integer to access an array, an object at the integer position is returned. If there is no object at this position, Nil is returned. Use a negative integer to access the array, and count from the end of the array

 

You can use a pair of numbers [start, Count] to access the array. This will return a new array containing the reference from the start or count objects.

 

You can also use range to index the array. Its start and end locations are separated by two or three vertices. The form of two vertices contains the end position, but the form of three vertices does not contain

The [] operator has a corresponding [] = operator, which can be used to set elements in the array. If the subscript is a single integer, the element at the position will be replaced by something on the right of the value assignment statement. Any gap caused is filled by nil.

 

  • Hash

It can also be associated with arrays, graphs, and dictionaries. Hash can be indexed by any type of objects, such as strings and regular expressions. When you store a value in the hash, you need to provide two objects, one is the index (usually called the Key), and the other is the value.

  • Block

First, the block only appears in the Code together with the method call. The last parameter of the block and method call is in the same line, followed by it (or the right parenthesis of the parameter list)

Second, when a block is encountered, the code in the block is not executed immediately. Ruby will remember the context (local variables, current object, etc.) when the block appears, and then execute the method call

In the block definition, the parameter list is located between two vertical bars (pipe operators). A block can contain a certain number of parameters.

 

Returns all the columns in the ononacci sequence that are lower than a certain value:

 

If the parameters passed to the block are existing local variables, these variables are block parameters, and their values may change due to the execution of the block. The same rule applies to the variables in the block: If they appear in the block for the first time, they are the local variables of the block. On the contrary, if they first come out of the block, the block shares these variables with its external environment.

Defined? Method returns nil if its parameter is not defined

Inject iterator: allows you to traverse all the collected members to accumulate a value.

Inject works like this: when a block is executed for the first time, sum is set to the inject parameter, while element is set to the first element to be collected. Next, when the block is executed, sum is set to the return value when the block was called last time. The value returned by the last block call of inject. If inject does not have a parameter, it uses the first element collected as the initial value and starts iteration from the second element.

  • Closure (closure)

  • Number

Integer in a certain range

 

They are stored in binary format internally. They are fixnum class objects, and integers out of range are stored in bignum class objects.

Ruby automatically manages back-and-forth conversions between them.

When writing integers, you can use an optional leading symbol. The optional hexadecimal indicator (0 indicates octal, and 0d indicates decimal [Default]. 0x indicates hexadecimal or 0b indicates binary), followed by a string of numbers that conform to the appropriate hexadecimal format. Underlines are ignored in strings.

 

All integers are objects and can respond to messages in various forms. Ruby uses num. Abs instead of ABS (Num) to obtain the absolute value of a number.

Several useful iterators supported by integers:

Note the exclamation point at the end of the downcase method name. This identifier is used to indicate that the method will modify the receiver at an appropriate position. In this example, it converts the string to lowercase.

  • Interval

1. The first and most likely natural use of the interval is to express the sequence. In Ruby, use the range operators "..." and "..." to create sequences. Two vertices are used to create closed intervals (including values on the right), and three vertices are used to create semi-closed and semi-open intervals, excluding values on the right.

<=> The spacecraft operator compares two values and returns-, + 1 based on whether the first value is smaller than, equal to, or greater than the second value.

2. range as a condition: Here they act like a bidirectional switch-when the condition in the first part of the interval is true, they open. When the condition in the second part is true, they are closed. For example, in the following code segment, the set of rows obtained from the standard input is printed. The first line of each group contains the start word, and the last line contains the end word.

3. interval: Check whether some values fall into the interval of expression. This can be done using the ===( case when ity operator)

 

Programming Ruby Reading Notes

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.