Ruby programming language – Part 1

Tram Ho

The reading from one book – The ruby ​​programming language – was written in 2008, Ruby version 1.9

Copyright © 2008 David Flanagan and Yukihiro Matsumoto.

Cut off related parts of ruby ​​1.9 because it is too old, it may appear content that is not suitable with Ruby 2.6.5 version at the present time.


Chapter 1. Horseback riding to see flowers, skim over concepts

The chapter basically skips over ruby ​​usage and syntax, with additional notes that need attention.

1.1 Ruby is an Object-Oriented language

Any .class can be:


1.2 Blocks and loops

If python is 1000% object-oriented (including code), everything in ruby ​​is an object except a block. Some methods need to combine with blocks:

1.3 Expressions and operators

This has the same set of rules as python, php, java, C ++ => I know so there is nothing important to mention here. Read chapter 4 for more info.

1.4 Method

1.5 Assign

1.6 Prefix, suffix

global variables are prefixed with $, instance variables are prefixed with @, and class variables are prefixed with @@.

1.7 Regexp and Range

1.8 Classes, Modules

Set aside for Chapter 7 to read for comfort.

1.9 Two incredible features.

=> horror is more true.

  • Ruby’s strings are mutable . The << operator is used to concatenate strings. Use freeze to freeze a string. Use magic comments to immutable all strings in one file. https://bugs.ruby-lang.org/issues/8976#note-30 => A heated debate about whether to default immutale with strings in Ruby 3, instead of having to use magic comments at the top of the file like this:

Perhaps the only reason that ruby ​​allows the string to be changed is to improve the loop performance when a string is constantly changed (probably the type that modifies a string over and over again, without having to copy each element individually). (character) of that string is copied to a new object and then reassigned to the old object): imagine that a string must change continuously 1 million times will be faster than 1 million new strings are created to reassign the string to be changed

However, mutated variables are easy to cause errors, especially when multiple variables refer to the same object. Side effects of one method can change the behavior of another. The confusing appears because the variable name is not enough to predict the value content by itself. Dev must know the variable’s life cycle.

=> The non-mutation will help the code work better.

  • Conditional expressions in addition to false, Ruby accepts nil as false => When testing true and false, only false and nil are for false values. Everything else is true (including 0, 0.0, “”, and []).

Chapter 2. Language structure, Ruby program

2.1 Vocabulary structure

2.1.1 Comments

2.1.2 Style

The way rubies appear directly in source code, including numbers, text strings, and regular expressions. arrays and hashes, more complex expressions described in chapter 3 Datatype and objects

2.1.3 Punctuation

Punctuation marks can be used to make + , - , * , / operators. Sequence separator, Regular expression, array, hash. Group and separate expressions, method parameters, and aray indexes

All these things will appear scattered in the Ruby syntax that we code out.

2.1.4 Identifier

To name variables, methods, classes …

Identifiers include characters, numbers, underscores _ , but do not start with digits , do not include spaces, characters cannot be printed to the screen.

Identifiers are capitalized The first letter is a constant (usually to name a class or module), if the value changes will be warned by the interaction, not an error =)), irb :

And the constant is capitalized all HANG_SO = 1

Sensitive : ruby ​​is case sensitive => keyword end – not keyword END =))

Unicode In addition to ASCII, ruby ​​can also be written in Japanese (because ruby ​​language is created by the Japanese), SJIS or EUC charsets include the Kanji alphabet in Japanese. However, special rules are based on ASCII.

Punctuation used in identifiers

  • Starts with $ => using global variable declaration
  • @ instance variable
  • @@ class variable
  • ? is simply the application of coding convention, which means True or False reutrn
  • ! means caution because in addition to the guard value it also changes the object’s intrinsic (but not all, ex: exit! will stop the program immediately)
  • = assign value

2.1.5 Sets of Keywords ruby

Not much, but not necessarily used up:

2.1.6 Space mark

Space, tab, and a white line all mean token token.

Most spaces are ignored by the interpreter, only some spaces are required.

Some cases of inserting or removing a space change the meaning of a program.

2.2 Syntax structure

This section briefly describes how to incorporate the vocabulary of Section 2.1 the program to create a ruby, from the most simple expression, until the large module with multiple functions.

About initializing the basic data structure: array, hash and range:

Original expressions: numbers, variables, assignments, assigns 2 operators combined

Conditional expression:

2.2.1 Block structure in Ruby

A block is a block of code associated with an iterative method.

2.3 Structure of a ruby ​​file

  1. The “shebang” comment tells the compiler how the program works on the system
  2. If the ruby ​​program has to be readable, then comment on the second line (if there is the first line).
  3. __END__ the interpreter will stop reading the code here, the rear character can be used as an I / O program data
  4. Download the code from another file using require

2.4 Encrypt the program

# coding: utf-8 # -*- coding: utf-8 -*- # vi: set fileencoding=utf-8 : the result is the form:

Basically imitating python: https://www.python.org/dev/peps/pep-0263/ => ruby ​​like python’s brother =)) learning python can turn to learning ruby ​​and vice versa. Use the following parameter to specify encoding when executing a ruby ​​program using the shell command

But ruby ​​2.1 and above utf8 encoding by default should not need to declare => haizZ, too much work to write this paragraph, reading old books is so painful !!!

2.5 Execute the program

Interpreter => Read file, Execute the defined classes, then run any of the following lines written after the so-called BEGIN. Stop only when encountering 1 of 3 cases:

  1. Meeting the command causes the ruby ​​program to stop.
  2. met end of file
  3. Read the logical end of the file with the token __END__

Chapter 3. Data types and base objects in ruby

3.1 Number

Ruby has 5 built-in classes to represent numeric data types:

Numbers with values ​​in the range of 31 bits are FixNum, otherwise they are BigNum. BigNum is the result of a calculation on the operands (the result has a value that does not fit FixNum).

Complex numbers, floating point numbers, and rational numbers are not built into Ruby, but are distributed with Ruby as part of the standard library.

3.2 String

irb:

Note the difference between using single quotation chain ' and the quotation " : string interpolation value to be transmitted only when using quotation.

Use Unicode escapes to use other ASCII characters.

3 Ways to print documents without having to add in front apostrophe or quotation or characters is explained in another in a string:

Write heredoc (here doc is a way of reporting string with multiple lines):

Execute commands with ubuntu shell, irb :

As mentioned in 1.9, the string in ruby ​​is mutable, so the interpreter cannot use the same object for a string. You should avoid duplicating with direct initialization string, every time you encounter a string of ruby ​​characters, you will create a new object on memory


Some common non-expressive characters, such as line breaks, tables, special symbols, need to use alternate characters:


Operators with strings vs Access , Cut , iterate this 2 part practice when doing projects, they know. Writing it down is even harder to understand: v

3.3 Arrays, Hashes, Range, Symbol

This part of the book is all about basic lines, working with arrays, hashes, ranges so familiar, so reading this section will feel bored all over.

Ruby Hashes <=> Python Dictionary, in C ++, Java, PHP is still called Associative Arrays, hash is simply a data type similar to array but index is not default but specified.

A symbol is a data type in ruby, simply understand that the string cannot be changed in ruby, ruby ​​stores all symbols in memory with symbol table every time a new symbol is created.

3.4 True, False, and Nil

ruby differs from other languages ​​in that these 3 are all objects, characteristics are neatly presented in 1.9.

3.5 Objects – Funny shapes

Ruby’s hegemony is that everything is an Object, making this part a bit bulleted to write:

3.5.1 Reference

Regardless of the subject’s name, where it is, gender can be changed, except that the ID card is one and the same.

The real nature of working with objects in ruby ​​is working with Object References .

=> When assigning a value (object) to a variable => essentially attaching the object’s reference to that variable. => Handling variables is essentially handling objects that the variable points to .

Illustration:

In other ways, when passing a variable to the params method, it is a direct reference to the value. In other words, it should be said that passing values ​​is rather than referencing. But the value passed in essence is the reference of the object (not the reference of the reference).

Because object references are passed to the method, the method can essentially modify the object. This change is applied when the method returns .

Instantaneous value . Different from the reference to the object. Fixnum and Symbol objects are instant values, both classes have transform methods, so Fixnum and Symbol objects are immutable , which means there’s no way to manipulate values ​​other than use reference. (Eg can not edit, delete, transform, can only reference to use)

The only difference used in practice is that instant values ​​cannot have singleton methods defined on them (they are Fixnum or Symbol objects), singleton methods are explained in Chapter 6.1.

3.5.2 Object life

Jack (Jack is my way of abstracting how to call an object in every object in ruby)

Mr. Jack (Object) is born on memory after the .new ( myClass.new ) statement. Jack gets his soul after the soul call initialize . As soon as Jack was born by ( .new ) Jack gained the human form by vaccines (params) injected directly into .new . These vaccines help Jack perfect the attributes needed for his body state, get the soul and become an object that exists in the ruby ​​process.

By default, Jack will be created like that, but there is another way, defining methods, called “factory methods” (Chapter 7.4).

3.5.3 Identity

If an ID card is used to identify a person, everyone has a unique fingerprint, unlike anyone.

Jack has an identifier, Identifier is unique until he dies. It’s jack.object_id

3.5.4 Class and type

To jack on a perfect day, jack must have a degree

Jack studied through a variety of classes from primary to regular university. That is called inheritance. Imagine that the company Jack is working on has an internship training model that can train a large number of new graduates, before when the company model was small, the former Internship was formerly TrainningStaff. It is also a class to help train young employees for the company.

However, regardless of the product of the training facility, what the company needs is the skills and skills of its employees

So companies can recruit probationers from Internship or from outside, which means there are many “types” of probationers that can recruit at the company. The type of employee trained from the Internship will be able to read the internal or popular ‘BaseDocument’ documents within the company, but the type of employee transferred from another company will be able to read some other types of specialized documents ( SaleDocument, AnalyticDocument, …). That is all read the document, but what kind of document, only the corresponding type of staff can do well. Therefore, the company needs to consider “employees” type to arrange jobs appropriately:

=> Type checking is referred to as the ruby ​​programming style, the “duck typing.” Chapter 7

3.5.5 Compare with

In this world, we will always compare with their children, but comparing there are many aspects that uncle not only learn well.

The object consists of 2 parts of id on memory and its own value, so there are up to 5 types of comparison between the two objects, these 5 cases:

  • equal?

  • eql?

  • == less strict than .eql? , only compare values ​​(including data types that can be converted, eg Fixnum can cast type to Float)

  • === called other similar cases == equality

Therefore, this operator is a bit different, so it should not be used commonly , only in specific cases.


  • = ~ Basic Regex matching operator. Not really a comparison operator by. Added to the list of operators for … full set => WTF this ruby ​​father


3.5.6 Operands comparing operands

Before making a decision, it is necessary to evaluate who is better than whom.

The present Numer class can be pre-defined for comparison (since it is a number), but if another class also defines an order, then class instances can be compared and sorted “like with numeric type “.

eg text in ASCII tables, can also be compared if ordered

The <=> operator returns 1, 0, -1 indicating the result of comparing 2 operands

However, this method is not intuitive so we can use it in the familiar way, thanks to the **Comparable** mixin that defines the following operators, each operator is a conditional case of <=> :

  • <
  • <=
  • ==
  • >=
  • >
  • between?

Modules and mixins => see Chapter 7

3.5.7 Convert to another object

Easy to change another lifestyle is an interesting thing in life.

  • The classes String , Integer , Float , Array define extremely conversion methods very eazy. to_s , to_i , to_f , to_a
  • The type of object when converting of course need a similar “style” to be new. For example: [[:a, 1], ["b", 2]] can switch styles with {:a=>1, "b"=>2} and vice versa.

3.5.8 Copy

This is exactly Cloned

jack.dup will create another jack , 2 jacks are identical to everything except the object_id identifier (the identities of the string properties copied inside the object will also change – because the string in ruby ​​is mutable) . If type a = “abc” then b = a.dup is equivalent to b = "abc" , not b = a .

3.5.9 Textualization of objects

(Save object state to I / O file)

3.5.10 Freeze the object

Entering the Ice Age

.freeze will freeze all properties of an object => simply the object cannot be changed anymore.

3.5.11 Poisoned object

Outlaws

When marked as taint => this object means intoxication, which can be dangerous, all objects arising from this object will also be marked.

User input, such as command line arguments, environment variables, and reading any string with gets will be automatically poisoned.

Web applications often have to monitor unreliable user input data to avoid SQL injection attacks and similar security risks.


Chapter 4. Expressions and operators

This chapter does not matter, but it will still be a review of how to use ruby ​​expressions, operators, and syntax.

4.1 Characters, keywords

Basically, Chapter 2 introduced the application of the keyword built by ruby. Regarding the use of variables, in any context we can see there are always available reference variables such as nil , true , false , self , __FILE__ , __LINE__ , __ENCODING__ .

4.2 Variables

As explained in Chapter 2, there are four types of variables in Ruby and the lexical rules for managing biến relatives: v:

  • Variables beginning with $ are global variables, which appear throughout a Ruby program
  • Variables that start with @ and @@ are “instance variables and classes”
  • And whose names start with an underscore or lowercase letters are local variables, only defined in the current method or block . The scope of this variable should be clearly described in Chapter 5.

In general, you must always assign values ​​to or initialize your variables before using them in expressions. However, one puzzling occurs if the variable has never been declared:

  • global variable call: return nil , in “ruby classic movie” wherever you are, there is always a first-person galaxy, and who it is depends on the movie’s performance: v
  • Call Class variables: raise NameError => before the movie held the press conference to announce what kind of protagonist.
  • Calling Instance variable: returns nil The extra character that can leave the movie still going on
  • The scriptwriter said the story had a guy named độc cô cầu bại , and what kind of guy it was was not assigned by the director because there was no actor qualified to cast. As for the đông phương bạch guy, who is not the main character in the movie, he was removed from the script (the writer was so angry and could not do anything: v):

=> What a bit and this and that = but only ignored.

4.3 Constants

The Ruby interpreter doesn’t actually execute the state of a constant, but it does warn if a program changes the value of a Constant. Constants are declared by the class as a normal variable, except the variable name must be VIET_HOA, or Viet_Hoa. However, the declaration of Viet_Hoa constant is often used for Module and Class naming. The :: sign to separate the parameter defined within the module: TenModule :: TEN_HANG_SO. Say using the constant as a variable.

4.4 Call the method

Just calling the method only makes it divided into 4 parts:

  • dấu gọi a method is . followed by the method name, the :: sign is also used to call constants (remember that TênClass , TênModule also constants)
  • method tên
  • Argument values ​​are passed to the method. The list of arguments can be enclosed in parentheses, but they are usually optional. (The options and mandatory parentheses are discussed in detail in Chapter §6.3. The space 2.1.6 means the token token fall.) If there is more than one argument, they are separated by commas. The number and type of arguments depend on the method definition. Some methods don’t expect arguments.
  • An optional block code is separated by curly braces {} or in do / end pairs. Methods can execute code within this block by using the yield keyword. This ability to arbitrarily associate block code with any method call and is the basis for Ruby’s powerful iterative methods that coders always use, such as in 2.2.1 (map, reduce, inject, times, upto, downto, step …. guys don’t use blocks)

Continue …

Share the news now

Source : Viblo