In Ruby, objects are the basic unit, so all elements are objects. In our previous understanding of object-oriented programs, an object is a group of programs that contain a specific set of properties and methods. An object is defined by a class and is represented as an object instance. That is, an object is an instantiation of a class [2].

The basic elements of the Ruby language

Objects: numeric objects, string objects, regular expression objects, time objects, file objects, directory objects, arrays, hashes, exception objects, etc

Numerical object

* * * *

Since all data in Ruby is objects, the numbers we work with are actually objects.

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

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

Variables in Ruby also do not need to be typed when they are declared, somewhat similar to the weakly typed language PHP. But when a variable is used, its type is determined.

Constants: Variables that begin with a capital letter are constants

Reserved words in Ruby

In Ruby, line breaks are commonly used as statement splits and can also be used. To act as a semantic separator. In the writing process of the program, we should pay attention to maintain a good writing style.

The operator

Operand operator

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

Comparison operator

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

The == operator can only compare two object values. If you want to compare objects, you need to use the specific method obj1.eql? (obj2), obj1. Equal? (obj2)

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

In Ruby, methods that return True or False are usually named with? Endings, such as Def AreUSure? ().

Logical operator

, &&, | |, and, or

An operator

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

True and false values in Ruby

In Ruby, both false and nil are false when judging, and all other values are true. Nil is a special value used in regular expressions to indicate that no match was found. That is, 0 is also true in Ruby.

In Ruby Symbol

In Ruby Symbol stands for “name”, such as the name of a string or identifier. A Symbol object is created by prefixing the name or string with a “:”. Every Object in Ruby has a unique Object Identifier, which can be obtained using the object_id method (Getter).

In Ruby Block

Code blocks are one of Ruby’s most powerful features, but one element of its design that is not easily understood. In Programing Ruby, it is pointed out that blocks can be used to implement some iterators in Ruby, such as:

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

There are two ways to define a Block: {} and do/end. The former is more suitable for single-line programs and the latter is more suitable for multi-line programs. Examples are as follows:

def greet(name)

print “Hello #{name} “

yield

end

greet(“Wang”) do

print “Hi”

end

Blcok must follow the method call and initiate the execution of the Block by yield in the method.

Control statements

Conditional statement

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

     if  condition then

          block 1

     else

          block 2

     end

You can have multiple branches

     if condition then

          block 1

     elsif condition then

          block 2

     else

          block 3

     end

Ruby provides the opposite of the if conditional statement unless

     unless condition then

          block 1

     else

          block 2

     end

Branch decision statement

     case condition

     when value1 then

          block 1

     when value2 then

          block 2

     else

          block 3

     end

It is worth mentioning that the judgment in the case statement is not only the judgment of the value of the variable, but also the judgment of the object type and the judgment of the regular expression. Therefore, the Ruby case statement can be very powerful when used.

Loop control statement

Loop control statements are used when we want to repeat some action. When we use loop control statements, we need to pay attention to two points: one is the condition of the loop and the other is the number of loops.

Ruby provides three loop control statements: for, while and until, and three loop control methods: each, times and loop. We can choose different methods according to our needs.

     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 control statements: break, next, and redo.

Classes, methods, and modules in Ruby

Ruby classes in the

A class is a description of an object’s behavior and properties. As an object-oriented scripting language, Ruby supports the concept of classes, class definition, inheritance (no more than one parent class is allowed), restricted access to methods, Setter and Getter Settings, and so on.

The definition of a 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

Class access qualifier

Three method access qualifiers, public, private, and protected, are available in Ruby to restrict access to individual or batch methods. Access qualification can be applied to a single method individually or to multiple methods in a batch manner.

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

Class inheritance

     class People

     end

     class Male < People

     end

Modules in Ruby

The concept of namespaces?

Module definition

     module moduleName

     end

When using modules in other files, you first need to include the module file with require, AutoLoad? . A module can be introduced into a class so that the methods of the module become the methods of the class. You can use this trick to implement multiple inheritance in Ruby.

Methods (Functions) in Ruby

Methods in Ruby are divided into instance methods, class methods, and functional methods. The distinction is based on method recipients.

The way instance methods are used, the definition of instance methods is actually done in the class.

     object.method( argument1, argument2, argument3 )

How class methods are used

     f = File.open( filename )

Definition of functional methods

     def functionName( parameter1, parameter2 = “default value”)

          block

          return

     end

A functional method can omit a return statement, in which case the return value of the function is the value of the last statement in the method, just as Perl does. Omitting Return statements can make code writing easier, but we need to be careful.

Ruby functions can return multiple values, such as:

     a, b, c = funca()

Error and exception handling

Writing any program can occur errors, including syntax errors, logic errors. Accidents can also occur, such as accidental hardware damage. So when we write a program, we have to consider all possible contingencies. In languages with no exception processing, we need to make judgments about every possible error. Fortunately, Ruby provides exception handling, which makes our work a lot easier.

A general form of error handling

     begine

          block

     rescue=> ex

          print ex.message

          block

     ensure

          block

          retry

     end

Resuce is provided in Ruby to handle errors when exceptions are encountered, ensure that the code below it executes in any case, and retry retries code from Begin. By default $! Returns an exception object, and $@ returns exception information.

Ruby provides a catch throw syntax, but this seems quite different from other languages.

Ruby provides a standard exception class with numerous subclasses to represent different exceptions.

Commonly used classes in Ruby

Numeric class

The Numeric class includes four subclasses Integer, Fixnum, Bignum and Float, as shown in the following figure.

To facilitate Math, Ruby provides the Math module, which makes it easy to calculate trigonometric functions and other formulas.

Array class

An array is a very important element in any language. Arrays provide a container of data that can be quickly traversed and accessed through indexes.

Arrays in Ruby can play three roles: plain indexed arrays, collections, and queues. With these three different uses, we can use arrays to implement FIFO, LILO and other data structures.

Arrays can be created in several ways:

1. Use [].

2. Use array.new

Perl-like array creation using %w.

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

5. Split the string into an array using the split method.

The Array class provides a number of functions for manipulating 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. d. elete, a. d. elete_at (), a. d. elete_if {| item |… }, a.r eject (| item |), a.r eject! (| item |), a.s lice! (), a.uniq(), a.uniq! (), a.c ollect {| item |… }, a.c ollect! {|item| … {}, arjun ap | item |… }, arjun ap! {|item| … }, a.ill (), a.ill (value,begin), a.ill (value,begin,len), a.ill (value,begin,len), a.ill (value, n.. M), a.lattern (), a.lattern! (), a.leverse (), a.leverse! (), a.sort(), a.sort! (), a.s ort {| I, j |… }, a.s ort! {|i,j| … }, a.s ort_by () | | I… , etc.

For Array traversal, we can use a loop with an index, or we can use some of the functions provided by Array. Array provides a class of functions that do not change the contents of the Array. These are called non-destructive methods. Methods that change the contents of the Array are called destructive methods. For functions provided in both ways, the destructive method is usually followed by! To differentiate. We should pay special attention to it when using it.

The String class

String is a very common data type in program development. In Ruby, there are ways to create new strings:

1, directly use “or ‘new

2. String. New Creates a new String

3. Create a file using %Q and %Q

Like Array, there are some common methods to call, such as is_A, delete, size, slice, etc. (Really? A little doubtful).

In strings, note the inline expressions, such as “A string is #{value}”, and the inline Document Here Document. These two methods, which are also common in scripting languages like PHP, can be very handy for handling variables and multi-line text output.

Another concern is the encoding of strings. For Western European characters, if we use ASCII encoding, then we can assume that the length of the string is equal to the length of the bytes in which the string is stored. However, when processing Chinese or other similar characters, it is often not possible to use a byte to store the characters, so the length of the string will be inconsistent with the length of the bytes.

In the program development, the common operations of string processing include: removing Spaces before and after (chomp), removing newlines at the end of lines (strip), finding strings, replacing strings (sub, gsub, tr, re, etc.), intercepting strings (index, function), calculating the length of strings, etc.

Hash class

As a data structure, Hash has high access speed and plays an important role in processing some key-value scenarios.

The hash object in Ruby can be created in {} or hash. new. Theoretically, the Hash key can be any object, but in practice, we usually choose Numberic, String, and Date as key values, because such key values are more accurate in comparison, while the comparison of other objects is more complicated.

Ruby provides batch and iterative methods for retrieving keys and values, making it easy to retrieve the contents of objects.

Regular Expression classes (Regexp)

The history of regular expressions goes back to the earliest days of scientists’ understanding of how the human nervous system works. Warren McCulloch and Detroit-born Walter Pitts, two neurophysiological scientists, have developed a new mathematical way to describe neural networks. They have innovatively described neurons in the nervous system as small, simple, autonomous units. Thus a great innovation of work was made.

The origins of regular expressions lie in automata theory and formal language theory, both of which are part of theoretical 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 regular sets.[1] The SNOBOL language was an 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 regular expressions (“grep” is a word derived from the command for regular expression searching in the ed editor: g/re/p where re stands for regular expression[2]). Since that time, many variations of Thompson’s original adaptation of regular expressions have been widely used in Unix and Unix-like utilities including expr, AWK, Emacs, vi, and lex.

Regular expressions were developed for more complex string matching.

In Ruby, there are several ways to create regular expression objects: //, regexp.new (), %r, etc.

The metacharacters of regular expressions in Ruby are consistent with regular expressions in other languages.

The String class provides methods sub, gsub, and scan to receive regular expression objects.

IO class

IO is an essential part of every programming language. Usually IO has three types: standard input, standard output, and error output.

For Console, Ruby uses $stdin, $stdout, and $stderr.

File IO is the one we use most often in programming. Ruby, like other languages, provides functions such as open, close, seek, popen, gets, readline, and read to help you read, modify, and save files.

The File and Dir

The IO class provides standard methods for manipulating input and output, but files and directories are often used in File systems. Ruby provides File and Dir classes, as well as auxiliary classes such as FileTest and Fileutils. To help us more convenient programming.

Time, Date, DateTime classes

If you look at these three classes and you’re not familiar with them, you might ask why are there so many classes for time processing?

Processes and threads in Ruby

Fiber, Thread, Process.

Fibers provides the ability to suspend one part of a program and then execute another. In fact, Fiber is not multithreaded in the full sense of the word, because the execution of the program is interrupted and the single thread is still executing. The basic form is as follows:

fiber = Fiber.new do

     Fiber.yield 1

     2

end

puts fiber.resume

After Firber is created, it does not run automatically. Instead, it waits until Fiber#resume is called to start executing statements within the block. After fiber. yield is reached, execution of the program is suspended until the next call to Fiber#resume or the execution of the program ends.

The Thread.

Prior to 1.9, Ruby multithreading was implemented by the interpreter, and after 1.9, it was implemented by the system. One problem with this is that many Ruby extensions are not Thread Safe, so you sometimes run into problems and need to be aware of this. How to create Thread.

threads = []

10.times{

     threads << Thread.new(parameter) do |p|

     end

}

threads.each{ |thr| thr.join  }

Tools in Ruby

Ri Document viewer tool. Ri Options Names is a handy way to view Ruby documentation.

Irb Uses irBS for interactive programming.

References:

1. Ruby Programming

2. Baidu Encyclopedia – Definition of objects

3. Baidu Encyclopedia -Ruby on Rails

4, Ruby Doc

5, Baidu Encyclopedia – regular expressions

Stephen Cole Kleene

7, Programming Ruby by Dave Thomas

Symbol in Ruby

9, Ruby Symbol study