Ruby Learning Notes

Source: Internet
Author: User
Tags bitwise operators ruby on rails

In the Ruby language, the object is the basic unit, and all of the elements can be said to be objects. As previously understood for object-oriented programs, an object is a set of programs that contains a collection of specific properties and methods. An object is defined by a class and behaves as an object instance. That is, the object is an instantiation of the class [2].

Basic elements of the Ruby language

Objects: Numeric objects, string objects, regular expression objects, time objects, file objects, directory objects, arrays, hashes, exception objects, and so on

Numeric objects

Since all data in Ruby is an object, the numbers we deal with are actually objects.

A = 10, such a simple assignment statement, should actually be understood as an instantiation form of a = Numeric.new (10).

Variables: Local variables (lowercase letters or _), global variables ($), instance variables (@), class variables (@@), virtual variables.

A variable in Ruby does not need to specify a type when declaring it, which is somewhat similar to PHP in weakly typed languages. But when a variable is used, his type is determined.

Constants: Variables that start with a capital letter are constants

Reserved words in Ruby

Ruby is usually broken up as a statement or used as a semantic separator. In the process of writing the program, we should pay attention to maintain a good writing style.

Operator

Manipulation operators

+ 、-、 *,/,%, * *

Comparison operators

>=, <=, = =, <>, = = =

The = = operator can only compare two object values, and if you want to compare objects, you need to use a specific method obj1.eql? (OBJ2), obj1.equal? (OBJ2)

For numeric objects, the comparison method is customized, so the results are somewhat different.

In Ruby, for this method of returning true or FALSE, the name is generally in the? End, such as Def Areusure? ()。

logical operators

&&, | |, and, or

Bitwise operators

&, |, ~, ^, >>, <<

Truth and false values in Ruby

In Ruby, false and nil are false when judged, and all other values are true. Nil is a special value that is used in regular expressions to indicate that no matching content is found. That is, 0 is the truth in Ruby.

The symbol in Ruby

In Ruby, symbol means "name", such as the name of the string, the name of the identifier, and the way to create a symbol object is to precede the name or string with ":". Each object in Ruby has a unique object identifier (Identifier), which can be obtained using the object_id method (Getter).

Block in Ruby

Blocks code block is a powerful feature of Ruby, and it's not an easy one to understand the design principle. In the book programing Ruby, the existence of blocks can be used to implement some of the iterator in Ruby, such as:

Array.each {|index| Print Array[index]}

Block is defined in two ways, one is {} and the other is do/end. The former is better suited for writing a single-line program, and the latter is more suitable for multi-line programs. Specific examples are as follows:

def greet (name)
Print "Hello #{name}"
Yield
End
Greet ("Wang") do
Print "Hi"
End

The Blcok must follow the method invocation, starting with the yield of the method and the execution of the block.

Control statements

Conditional Judgment Statement

When the condition is true, the contents of the corresponding block are executed.

If condition Then

Block 1

Else

Block 2

End

You can also have multiple branches

If condition Then

Block 1

elsif condition Then

Block 2

Else

Block 3

End

Ruby provides a conditional judgment statement in contrast to the IF unless

Unless condition then

Block 1

Else

Block 2

End

Branch Judgment Statement

Case condition

When value1 Then

Block 1

When value2 Then

Block 2

Else

Block 3

End

It is worth mentioning that the case statement is not only the judgment of the value of the variable, but also can make the object type of judgment, can also make the regular expression of judgment, so Ruby Case statement used, the function can be very powerful.

Loop control Statements

loop control Statements Use circular control statements when we want to repeat some actions, with two points to note: One is the condition of the loop and the number of cycles.

Ruby provides a for, while, until three loop control statements, each, times, loop three loop control methods, we can choose a different way as needed.

While condition do

Block 1

End

For variable in object do

Block

End

Until condition do

Block

End

object.each{|variable|

Block

}

Number.times {| index variable |

Block

}

Loop {

Block

}

Ruby also provides three loop-controlled statements, including break, next, and redo.

Classes, methods, and modules in Ruby

Classes in Ruby

A class is a description of the object's behavior and properties. As an object-oriented scripting language, Ruby supports the concept of classes, supports the definition of classes, inheritance (does not allow inheritance of multiple parent classes), the scope of access to qualified methods, setter and getter settings, and so on.

Definition of Class

Class ClassName

Version = "1.0"

Attr_accessor:name

DEF initialize (parameter)

End

Public

def publicMethod1

Block

End

def PUBLICMETHOD2

Block

End

Private

def privateMethod1

Block

End

def PRIVATEMETHOD2

Block

End

End

Access qualifier for Class

The public, private, protected three method access qualifiers are available in Ruby to restrict access to individual or bulk methods. You can restrict access to individual methods individually, or you can use Access qualification for multiple methods in a batch manner.

By default, all methods are public, except for initialize, which is always a private method.

Inheritance of Classes

class people

End

Class Male < people

End

Modules in Ruby

The concept of namespaces?

Definition of the module

Module ModuleName

End

When using modules in other files, you first need to use require to include the module files in, AutoLoad?. Modules can be introduced in a class so that the method of the module becomes the method of the class. You can use this little trick to implement multiple inheritance for Ruby.

Methods (functions) in Ruby

Methods in Ruby are distinguished as instances of methods, methods of classes, and functional methods. The distinction is based on the difference of the method recipient.

How the instance method is used, the definition of the instance method is actually done in the class.

Object.Method (argument1, argument2, Argument3)

How class methods are used

f = file.open (filename)

Definition of a functional method

def functionname (parameter1, parameter2 = "Default value")

Block

Return

End

The function method can omit the return statement, at which point the return value of the function is the value of the last statement in the method, just like the Perl process. Omitting the Return statement can bring some convenience to code writing, but we need to be cautious.

Ruby's functions can return multiple values, such as:

A, b, C = Funca ()

Error and exception handling

Writing any program can cause errors, including syntax errors and logic errors. Some accidents can occur, such as accidental damage to hardware. So when we write the program, we need to think about all the possible surprises. In languages without exception handling, we need to judge each of the possible errors. Fortunately, the exception handling mechanism is provided in Ruby, which greatly reduces our workload.

General form of error handling

Begine

Block

Rescue=> EX

Print Ex.message

Block

Ensure

Block

Retry

End

Resuce is provided in Ruby to handle error handling when an exception is encountered, and ensure ensures that whatever the case is, the code portion of it will be executed retry re-attempt the code starting from begin. By default $! Returns the exception object, [email protected] Returns the exception information.

Ruby provides the syntax for catch throw, but this seems to be quite different from other languages.

Ruby provides a standard exception class with a number of subclasses that represent different exceptions.

Common classes in Ruby

Numeric class

The numeric class includes Integer, Fixnum, Bignum, and float four subclasses, as shown in the relationship.

In order to facilitate mathematical operations, Ruby provides math modules that can be easily used for trigonometric functions.

Array class

Arrays are an important element in any language, and arrays provide a container for data that allows us to quickly traverse and access the required data elements through an index.

Arrays in Ruby can play three roles: normal indexed arrays, collections, queues. By using these three different ways, we can use arrays to realize a variety of data structures such as FIFO, Lilo and so on.

There are several ways to create an array:

1, use [].

2. Using Array.new

3. How to create an array similar to Perl, created using%w.

4. Use the Obj.to_a method to convert an object to an array.

5. Use the Split method to split the string into arrays.

The array class provides a number of functions to facilitate the operation of arrays, including: arr.at (Index), Arr.pop (), Arr.push (value), Arr.shift (), Arr.unshift (value), Arr.last (), Arr.first (), Arr.next (),

, Arr.slice (), Arr.values_at (), Arr.concat (), A.compact (), a.compact! (), A.delete (), A.delete_at (), a.delete_if{|item| ...}, A.reject (|item|), a.reject! (|item|), a.slice! (), A.uniq (), a.uniq! (), a.collect{|item| ...}, a.collect! {|item| ...}, a.map{|item| ...}, a.map! {|item| ...}, A.fill (), A.fill (Value,begin), A.fill (Value,begin,len), A.fill (value, N.). m), A.flattern (), a.flattern! (), A.reverse (), a.reverse! (), A.sort (), a.sort! (), a.sort{|i,j| ...}, a.sort! {|i,j| ...}, a.sort_by (|i| ...), and so on.

For the traversal of the array, we can adopt the method of cyclic mate index, or we can use some functions provided by array. One of the functions provided by array does not alter the contents of the array itself, which is called a non-destructive method, and there are ways to change the contents of the array, which are called destructive methods. For the functions provided in both ways, it is usually added after the destructive method! To make a distinction. We should pay special attention to it when we use it.

String class

String, which is a very common type of data in program development. In Ruby, you create a new string in the following ways:

1, directly use "or" new

2, String.new New

3, the use of%q and%q way to create new

Because they are inherited from the object class, as with array, there are some common methods that can be called, such as is_a, delete, size, slice, and so on (really?). Somewhat doubtful).

In the string, you should be aware of the inline expression, such as "A string is #{value}", and the inline document here. These two methods, which are also very common in scripting languages such as PHP, can be very convenient for processing variables and multiple lines of text output.

Another problem to be concerned with is the coding of strings. For Western European text, if ASCII encoding is used, then we can assume that the length of the string is equal to the length of the byte that stores the string. However, when working with Chinese or other similar text, it is often not possible to use a single byte to store text, so the length of the string is inconsistent with the length of the byte.

In program development, the common operations of string handling include removing the front and back spaces (chomp), removing line breaks (strip), finding strings, replacing strings (sub, gsub, TR, regular, etc.), intercepting strings (indexed, functional), calculating the length of strings, and so on.

Hash class

Hash as a data structure, with a faster access speed, in the processing of some key-value play a significant role in the scene.

The Hash objects in Ruby are created in the following ways: {}, hash.new two. Hash key can theoretically be any object, but in practice, we generally choose Numberic, String, date and so on as the key value, because such a key value is more accurate in the comparison, and other objects are relatively complex comparison.

Ruby provides a way to get the bulk and iteration of key and value so that we get the content from the object.

Regular Expression class (Regexp)

The history of the

Regular expression can be traced back to scientists ' early studies of the workings of the human nervous system. Warren McCulloch of New Jersey and a two-bit neuro-physiological scientist born in Detroit, Walter Pitts of the United States, developed a new approach to describing neural networks mathematically, and they creatively described neurons in the nervous system as small, simple, automatic control elements. Thus a great work innovation has been made.

The origins of regular Expressions lie in automata theory and formal language theory, both of which is part of Theoretica L Computer Science. These fields study models of computation (automata) and ways to describe and classify formal languages. In the 1950s, Mathematician stephen Cole kleene described These models using his mathematical notation called re Gular sets. [1] The Snobol language was a early implementation of pattern matching, but not identical to regular expressions. Ken Thompson built Kleene ' s notation into the editor, QED as a means to match patterns in text files. He later added this capability to the Unix editor Ed, which eventually led to the popular search tool grep's use of Regula R Expressions ("grep" is a word derived from the command for regular expression searching in the Ed editor:g/re/p where R E stands for regular expression[2]). Since that time, many variations of Thompson ' s original adaptation of regular expressions has been widely used in Unix an DUnix-like utilities including expr, AWK, Emacs, VI, and Lex.

Regular expressions occur for more complex string matches.

In Ruby, there are several ways to create regular expression objects://, Regexp.new (),%r, and so on.

The metacharacters of Ruby's regular expression is consistent with regular expressions in other languages.

The String class provides sub, gsub, and scan three methods that can receive a regular expression object.

Io class

IO is an essential part of every programming language, typically IO has three, standard input, standard output, error output.

For console, Ruby is represented using $stdin, $stdout, $stderr.

File IO is one of the most commonly used programs in our daily programming. Ruby, like other languages, provides functions such as open, close, seek, Popen, get, ReadLine, read, and so on to help us complete the read, modify, and save operations of the file.

File and Dir classes

The IO class provides us with a standard way to manipulate input and output, but for files and directories we often encounter, the file and directory operations are often done, so Ruby provides the file and Dir classes, as well as Filetest, fileutils and other auxiliary classes, To help us make the program more convenient to write.

Time, Date, DateTime class

If you are unfamiliar with people who see these three classes, you will surely ask why so much about time-processing classes?

Processes and Threads in Ruby

Fiber, Thread, Process.

Fibers provides a part of the suspend program and then performs the ability to perform another part of the program. In fact, fiber is not a multi-threading in the full sense, because execution of the program interrupts, still a single thread is executing. The basic form is as follows:

Fiber = Fiber.new Do

Fiber.yield 1

2

End

Puts Fiber.resume

After the Firber is created, it does not run automatically, but waits until the Fiber#resume method call starts executing the statement inside the block. After encountering Fiber.yield, pause the execution of the program until the next call to Fiber#resume or the end of the program execution.

Thread.

Before 1.9, the multithreading of Ruby was implemented by the interpreter, and after 1.9, multithreading began to be implemented by the system. However, there is a problem, many Ruby extensions are not thread safe, so sometimes encounter problems, this need to pay more attention. The method by which thread is created.

Threads = []

10.times{

Threads << thread.new (parameter) do |p|

End

}

threads.each{|thr| Thr.join}

Tools in Ruby

RI document to see the sharp weapon. With the RI options names, it's really handy to see Ruby's documentation.

IRB uses IRB for interactive programming.

Resources:

1, Ruby programming Takahashi Levy righteousness

2, Baidu Encyclopedia-the definition of the object

3, Baidu Encyclopedia-ruby on Rails

4. Ruby Doc

5, Baidu Encyclopedia-Regular expression

6. Stephen Cole Kleene

7. Programming Ruby by Dave Thomas

8. Symbol in Ruby

9. Ruby's symbol Research

Ruby Learning 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.