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 3 | <span class="token number">0.</span> <span class="token keyword">class</span> <span class="token comment"># => FixNum</span> <span class="token number">0.1</span> <span class="token punctuation">.</span> <span class="token keyword">class</span> <span class="token comment"># => Float</span> |
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 2 3 | <span class="token number">3.</span> times <span class="token punctuation">{</span> print <span class="token string">"Ruby! "</span> <span class="token punctuation">}</span> <span class="token comment"># Prints "Ruby! Ruby! Ruby! "</span> <span class="token number">1.</span> <span class="token function">upto</span> <span class="token punctuation">(</span> <span class="token number">9</span> <span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token operator">|</span> x <span class="token operator">|</span> print x <span class="token punctuation">}</span> <span class="token comment"># Prints "123456789"</span> |
1 2 3 4 5 | a <span class="token operator">=</span> <span class="token punctuation">[</span> <span class="token number">1</span> <span class="token punctuation">,</span> <span class="token number">2</span> <span class="token punctuation">,</span> <span class="token number">3</span> <span class="token punctuation">,</span> <span class="token number">4</span> <span class="token punctuation">]</span> a <span class="token punctuation">.</span> inject <span class="token keyword">do</span> <span class="token operator">|</span> sum <span class="token punctuation">,</span> x <span class="token operator">|</span> sum <span class="token operator">+</span> x <span class="token keyword">end</span> |
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 2 3 4 | <span class="token keyword">def</span> <span class="token function">polar</span> <span class="token punctuation">(</span> x <span class="token punctuation">,</span> y <span class="token punctuation">)</span> <span class="token keyword">def</span> polar x <span class="token operator">=</span> <span class="token number">1</span> <span class="token punctuation">,</span> y <span class="token keyword">def</span> polar x <span class="token punctuation">:</span> <span class="token number">1</span> <span class="token punctuation">,</span> y <span class="token punctuation">:</span> <span class="token keyword">nil</span> |
1.5 Assign
1 2 3 | x <span class="token punctuation">,</span> y <span class="token punctuation">,</span> <span class="token operator">*</span> z <span class="token operator">=</span> <span class="token punctuation">[</span> <span class="token number">1</span> <span class="token punctuation">,</span> <span class="token number">2</span> <span class="token punctuation">,</span> <span class="token number">3</span> <span class="token punctuation">,</span> <span class="token number">4</span> <span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token punctuation">[</span> <span class="token number">1</span> <span class="token punctuation">,</span> <span class="token number">2</span> <span class="token punctuation">,</span> <span class="token number">3</span> <span class="token punctuation">,</span> <span class="token number">4</span> <span class="token punctuation">]</span> |
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 2 3 4 5 6 7 8 9 10 11 12 13 | <span class="token keyword">def</span> are_you_sure <span class="token operator">?</span> <span class="token keyword">while</span> <span class="token keyword">true</span> print <span class="token string">"Are you sure? [y/n]: "</span> response <span class="token operator">=</span> gets <span class="token keyword">case</span> response <span class="token keyword">when</span> <span class="token regex">/^[yY]/</span> <span class="token keyword">return</span> <span class="token keyword">true</span> <span class="token keyword">when</span> <span class="token regex">/^[nN]/</span> <span class="token punctuation">,</span> <span class="token regex">/^$/</span> <span class="token keyword">return</span> <span class="token keyword">false</span> <span class="token keyword">end</span> <span class="token keyword">end</span> <span class="token keyword">end</span> |
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. Usefreeze
tofreeze
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:
1 2 | <span class="token comment"># frozen_string_literal: true</span> |
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
1 2 3 4 5 6 7 | <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">002</span> <span class="token operator">></span> a <span class="token operator">=</span> <span class="token string">"abc"</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token string">"abc"</span> <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">003</span> <span class="token operator">></span> a <span class="token punctuation">[</span> <span class="token number">0</span> <span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token string">"b"</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token string">"b"</span> <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">004</span> <span class="token operator">></span> a <span class="token operator">=</span> <span class="token operator">></span> <span class="token string">"bbc"</span> |
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
1 2 3 4 5 6 7 | # bình luận vào đây # hoặc =begin Someone needs to fix the broken code below! Any code here is commented out ... =end |
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
:
1 2 3 4 5 6 7 | <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">001</span> <span class="token operator">></span> <span class="token constant">Abc</span> <span class="token operator">=</span> <span class="token number">1</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token number">1</span> <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">002</span> <span class="token operator">></span> <span class="token constant">Abc</span> <span class="token operator">=</span> <span class="token number">2</span> <span class="token punctuation">(</span> irb <span class="token punctuation">)</span> <span class="token punctuation">:</span> <span class="token number">2</span> <span class="token punctuation">:</span> warning <span class="token punctuation">:</span> already initialized constant <span class="token constant">Abc</span> <span class="token punctuation">(</span> irb <span class="token punctuation">)</span> <span class="token punctuation">:</span> <span class="token number">1</span> <span class="token punctuation">:</span> warning <span class="token punctuation">:</span> previous definition of <span class="token constant">Abc</span> was here <span class="token operator">=</span> <span class="token operator">></span> <span class="token number">2</span> |
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:
1 2 3 4 5 6 7 | __LINE__ __ENCODING__ __FILE__ <span class="token keyword">BEGIN</span> <span class="token keyword">END</span> <span class="token keyword">alias</span> <span class="token keyword">defined</span> <span class="token operator">?</span> <span class="token keyword">begin</span> <span class="token keyword">class</span> <span class="token class-name">module</span> <span class="token keyword">super</span> <span class="token keyword">def</span> <span class="token keyword">yield</span> <span class="token keyword">return</span> <span class="token keyword">rescue</span> <span class="token keyword">retry</span> <span class="token keyword">ensure</span> <span class="token keyword">redo</span> <span class="token keyword">self</span> <span class="token keyword">in</span> <span class="token keyword">undef</span> <span class="token keyword">unless</span> <span class="token keyword">if</span> <span class="token keyword">elsif</span> <span class="token keyword">else</span> <span class="token keyword">end</span> <span class="token keyword">then</span> <span class="token keyword">do</span> <span class="token keyword">and</span> <span class="token keyword">or</span> <span class="token keyword">not</span> <span class="token keyword">true</span> <span class="token keyword">false</span> <span class="token keyword">nil</span> <span class="token keyword">for</span> <span class="token keyword">case</span> <span class="token keyword">while</span> <span class="token keyword">when</span> <span class="token keyword">until</span> <span class="token keyword">break</span> <span class="token keyword">next</span> |
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:
1 2 3 4 | <span class="token punctuation">[</span> <span class="token number">1</span> <span class="token punctuation">,</span> <span class="token number">2</span> <span class="token punctuation">,</span> <span class="token number">3</span> <span class="token punctuation">]</span> <span class="token punctuation">{</span> <span class="token number">1</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token string">"one"</span> <span class="token punctuation">,</span> <span class="token number">2</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token string">"two"</span> <span class="token punctuation">}</span> <span class="token number">1.</span> <span class="token number">.3</span> |
Original expressions: numbers, variables, assignments, assigns 2 operators combined
1 2 3 4 5 | <span class="token number">1</span> x x <span class="token operator">=</span> <span class="token number">1</span> x <span class="token operator">=</span> x <span class="token operator">+</span> <span class="token number">1</span> |
Conditional expression:
1 2 3 4 | <span class="token keyword">if</span> x <span class="token operator"><</span> <span class="token number">10</span> <span class="token keyword">then</span> x <span class="token operator">=</span> x <span class="token operator">+</span> <span class="token number">1</span> <span class="token keyword">end</span> |
1 2 3 4 5 | <span class="token keyword">while</span> x <span class="token operator"><</span> <span class="token number">10</span> <span class="token keyword">do</span> print x x <span class="token operator">=</span> x <span class="token operator">+</span> <span class="token number">1</span> <span class="token keyword">end</span> |
2.2.1 Block structure in Ruby
A block is a block of code associated with an iterative method.
1 2 | <span class="token number">3.</span> times <span class="token punctuation">{</span> print <span class="token string">"Ruby! "</span> <span class="token punctuation">}</span> |
1 2 3 4 | <span class="token number">1.</span> <span class="token function">upto</span> <span class="token punctuation">(</span> <span class="token number">10</span> <span class="token punctuation">)</span> <span class="token keyword">do</span> <span class="token operator">|</span> x <span class="token operator">|</span> print x <span class="token keyword">end</span> |
2.3 Structure of a ruby file
- The “shebang” comment tells the compiler how the program works on the system
- If the ruby program has to be readable, then comment on the second line (if there is the first line).
__END__
the interpreter will stop reading the code here, the rear character can be used as an I / O program data- Download the code from another file using require
1 2 3 4 5 6 7 8 | #!/usr/bin/ruby -w shebang comment # -*- coding: utf-8 -*- coding comment require 'socket' load networking library ... program code goes here __END__ ... mark end of code program data goes here |
2.4 Encrypt the program
# coding: utf-8
# -*- coding: utf-8 -*-
# vi: set fileencoding=utf-8 :
the result is the form:
1 2 3 | <span class="token comment">#!/usr/bin/ruby -w</span> <span class="token comment"># coding: utf-8</span> |
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
1 2 3 4 5 | ruby -E utf-8 ruby -Eutf-8 ruby --encoding utf-8 ruby --encoding <span class="token operator">=</span> utf-8 |
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:
- Meeting the command causes the ruby program to stop.
- met end of file
- 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:
1 2 3 4 5 | <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">053</span> <span class="token operator">></span> puts <span class="token string">"ruby giải thích dấu \ ở cuối rằng dòng này bỏ qua "ký tự xuống dòng" "</span> <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">054</span> <span class="token operator">></span> <span class="token string">"nên sẽ đọc tiếp cả dòng này mới hoàn thành một lệnh statements"</span> ruby giải thích dấu ở cuối rằng dòng này bỏ qua <span class="token string">"ký tự xuống dòng"</span> nên sẽ đọc tiếp cả dòng này mới hoàn thành một lệnh statements <span class="token operator">=</span> <span class="token operator">></span> <span class="token keyword">nil</span> |
Note the difference between using single quotation chain '
and the quotation "
: string interpolation value to be transmitted only when using quotation.
1 2 3 4 5 6 7 8 9 | <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">062</span> <span class="token operator">></span> a <span class="token operator">=</span> <span class="token number">1</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token number">1</span> <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">063</span> <span class="token operator">></span> puts <span class="token string">"a = <span class="token interpolation"><span class="token delimiter tag">#{</span> a <span class="token delimiter tag">}</span></span> "</span> a <span class="token operator">=</span> <span class="token number">1</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token keyword">nil</span> <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">064</span> <span class="token operator">></span> puts <span class="token string">'a = <span class="token interpolation"><span class="token delimiter tag">#{</span> a <span class="token delimiter tag">}</span></span> '</span> a <span class="token operator">=</span> <span class="token comment">#{a}</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token keyword">nil</span> |
Use Unicode escapes to use other ASCII characters.
1 2 3 4 5 | <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">119</span> <span class="token operator">></span> <span class="token string">"u{A5}"</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token string">"¥"</span> <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">120</span> <span class="token operator">></span> <span class="token string">"u{3C0}"</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token string">"π"</span> |
3 Ways to print documents without having to add in front apostrophe or quotation or characters is explained in another in a string:
1 2 3 4 5 6 7 | <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">001</span> <span class="token operator">></span> <span class="token string">%q(Don't worry about escaping ' characters!)</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token string">"Don't worry about escaping ' characters!"</span> <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">002</span> <span class="token operator">></span> <span class="token string">%Q|"How are you?", he said|</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token string">""How are you?", he said"</span> <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">003</span> <span class="token operator">></span> <span class="token string">%-This string literal ends with a newlinen-</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token string">"This string literal ends with a newlinen"</span> |
Write heredoc (here doc is a way of reporting string with multiple lines):
1 2 3 4 | query <span class="token operator">=</span> <span class="token string">%Q( Article about heredocs )</span> |
1 2 3 4 | query <span class="token operator">=</span> <span class="token operator"><</span> <span class="token operator"><</span> <span class="token operator">-</span> <span class="token constant">HTML</span> <span class="token punctuation">.</span> chomp <span class="token constant">Article</span> about heredocs <span class="token constant">HTML</span> |
1 2 3 4 5 6 7 | type <span class="token operator">=</span> <span class="token string">"healthy"</span> table <span class="token operator">=</span> <span class="token string">"food"</span> query <span class="token operator">=</span> <span class="token operator"><</span> <span class="token operator"><</span> <span class="token operator">-</span> <span class="token constant">SQL</span> <span class="token constant">SELECT</span> <span class="token operator">*</span> <span class="token constant">FROM</span> <span class="token comment">#{table}</span> <span class="token constant">WHERE</span> <span class="token comment">#{type} = true</span> <span class="token constant">SQL</span> |
Execute commands with ubuntu shell, irb
:
1 2 3 4 5 | <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">020</span> <span class="token operator">></span> cmd <span class="token operator">=</span> <span class="token string">'echo Hello World'</span> <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">020</span> <span class="token operator">></span> <span class="token function">system</span> <span class="token punctuation">(</span> cmd <span class="token punctuation">)</span> <span class="token constant">Hello</span> <span class="token constant">World</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token keyword">true</span> |
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
1 2 | 10.times { puts "test".object_id } |
Some common non-expressive characters, such as line breaks, tables, special symbols, need to use alternate characters:
1 2 3 4 5 6 | <span class="token operator">?</span> <span class="token constant">A</span> <span class="token comment"># ký tự ASCII cho `A`</span> <span class="token operator">?</span> € <span class="token operator">==</span> <span class="token string">"u20AC"</span> <span class="token comment"># => true</span> <span class="token operator">?</span> t <span class="token operator">==</span> <span class="token string">"t"</span> <span class="token comment"># bằng với `TAB` trong ASCII</span> <span class="token operator">?</span> <span class="token constant">C</span> <span class="token operator">-</span> x <span class="token comment"># thay thế `Ctrl+X`</span> <span class="token operator">?</span> <span class="token number">111</span> <span class="token comment"># ký tự mã hóa thành 0111 hệ bát phân</span> |
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:
1 2 3 4 5 6 7 | s <span class="token operator">=</span> <span class="token string">"Ruby"</span> <span class="token comment"># Khởi tạo đối tượng string "Ruby" gán cho s</span> t <span class="token operator">=</span> s <span class="token comment"># gán giá trị của s cho t => Bản chất là trỏ t tới đối tượng "Ruby"</span> t <span class="token punctuation">[</span> <span class="token operator">-</span> <span class="token number">1</span> <span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token string">""</span> <span class="token comment"># Thay đổi đối tượng "Ruby"</span> print s <span class="token comment"># => trở thành "Rub"</span> t <span class="token operator">=</span> <span class="token string">"Java"</span> <span class="token comment"># trỏ t sang một đối tượng mới</span> print s <span class="token punctuation">,</span> t <span class="token comment"># Prints "RubJava". => s trỏ tới "Rub", t trỏ tới "Java"</span> |
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.
1 2 3 4 | jack <span class="token punctuation">.</span> <span class="token keyword">class</span> <span class="token comment"># Internship jack thuộc lớp thực tập sinh dành cho sinh viên mới ra trường</span> jack <span class="token punctuation">.</span> <span class="token keyword">class</span> <span class="token punctuation">.</span> superclass <span class="token comment"># TrainningStaff - tiền đề ban đầu đào tạo nhân viên chất lượng cao của cty - Sau này hoàn thiện và xuất hiện Intership jack đang làm việc</span> jack <span class="token punctuation">.</span> <span class="token keyword">class</span> <span class="token punctuation">.</span> superclass <span class="token punctuation">.</span> superclass <span class="token comment"># nil không còn lớp nào cao hơn</span> |
1 2 3 4 5 | jack <span class="token punctuation">.</span> is_a <span class="token operator">?</span> <span class="token constant">Internship</span> <span class="token comment"># True Jack là một thực tập sinh</span> jack <span class="token punctuation">.</span> is_a <span class="token operator">?</span> <span class="token constant">TrainningStaff</span> <span class="token comment"># True Jack cũng là một nhân viên được đào tạo bài bản</span> jack <span class="token punctuation">.</span> instance_of <span class="token operator">?</span> <span class="token constant">Internship</span> <span class="token comment"># True Jack là sản phẩm của lò đào tạo Internship</span> jack <span class="token punctuation">.</span> instance_of <span class="token operator">?</span> <span class="token constant">TrainningStaff</span> <span class="token comment"># False nhưng jack không phải học viên của lò đào tạo TrainningStaff, lớp Internship đã kế thừa các mô hình đào tạo của TrainningStaff.</span> |
However, regardless of the product of the training facility, what the company needs is the skills and skills of its employees
1 2 | jack.respond_to? :"reading_report_document_skills" # true nếu jack có kỹ năng đọc tài liệu. |
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:
1 2 3 4 5 6 7 8 9 | <span class="token keyword">if</span> jack <span class="token punctuation">.</span> is_a <span class="token operator">?</span> <span class="token constant">Internship</span> jack <span class="token punctuation">.</span> can_reading_report_document base_document <span class="token keyword">end</span> base_document <span class="token punctuation">.</span> <span class="token keyword">class</span> <span class="token comment"># => BaseDocument</span> <span class="token keyword">if</span> john <span class="token punctuation">.</span> is_a <span class="token operator">?</span> <span class="token constant">BusinessStaff</span> john <span class="token punctuation">.</span> can_reading_report_document analytic_document <span class="token keyword">end</span> analytic_document <span class="token punctuation">.</span> <span class="token keyword">class</span> <span class="token comment"># => AnalyticDocument</span> |
=> 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?
1 2 | a.object_id == b.object_id # làm việc như a.equal?(b) |
- eql?
1 2 3 | <span class="token number">1</span> <span class="token operator">==</span> <span class="token number">1.0</span> <span class="token comment"># true: so sánh giá trị (không so sánh địa chỉ tham chiếu)</span> <span class="token number">1.</span> eql <span class="token operator">?</span> <span class="token punctuation">(</span> <span class="token number">1.0</span> <span class="token punctuation">)</span> <span class="token comment"># false: nhưng so sánh thêm cả kiểu dữ liệu (class) Fixnum vs Float</span> |
- == less strict than
.eql?
, only compare values (including data types that can be converted, eg Fixnum can cast type to Float)
1 2 | <span class="token number">1</span> <span class="token operator">==</span> <span class="token number">1.0</span> <span class="token comment"># true</span> |
- === called other similar cases == equality
1 2 3 4 | <span class="token punctuation">(</span> <span class="token number">1.</span> <span class="token number">.10</span> <span class="token punctuation">)</span> <span class="token operator">===</span> <span class="token number">5</span> <span class="token comment"># true</span> <span class="token operator">/</span> d <span class="token operator">+</span> <span class="token operator">/</span> <span class="token operator">===</span> <span class="token string">"123"</span> <span class="token comment"># true</span> <span class="token builtin">String</span> <span class="token operator">===</span> <span class="token string">"s"</span> <span class="token comment"># true</span> |
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
1 2 3 4 5 | <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">098</span> <span class="token operator">></span> <span class="token operator">/</span> hay <span class="token operator">/</span> <span class="token operator">=</span> <span class="token operator">~</span> <span class="token string">'Ôhaythằngnày'</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token number">1</span> <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">099</span> <span class="token operator">></span> <span class="token string">'aiÔhaythằngnày'</span> <span class="token operator">=</span> <span class="token operator">~</span> <span class="token regex">/hay/</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token number">3</span> |
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
1 2 | <span class="token string">"b"</span> <span class="token operator">></span> <span class="token string">"a"</span> <span class="token comment"># do thứ thự b lớn hơn a 1 đơn vị trong ASCII</span> |
The <=>
operator returns 1, 0, -1 indicating the result of comparing 2 operands
1 2 3 4 5 6 7 8 | <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">135</span> <span class="token operator">></span> <span class="token string">"b"</span> <span class="token operator"><=</span> <span class="token operator">></span> <span class="token string">"a"</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token number">1</span> <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">136</span> <span class="token operator">></span> <span class="token string">"b"</span> <span class="token operator"><=</span> <span class="token operator">></span> <span class="token string">"b"</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token number">0</span> <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">137</span> <span class="token operator">></span> <span class="token string">"b"</span> <span class="token operator"><=</span> <span class="token operator">></span> <span class="token string">"c"</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token operator">-</span> <span class="token number">1</span> <span class="token number">2.6</span> <span class="token number">.5</span> <span class="token punctuation">:</span> <span class="token number">138</span> <span class="token operator">></span> |
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)
1 2 3 4 5 6 7 8 9 | <span class="token punctuation">[</span> <span class="token number">1</span> <span class="token punctuation">]</span> <span class="token function">pry</span> <span class="token punctuation">(</span> main <span class="token punctuation">)</span> <span class="token operator">></span> a <span class="token operator">=</span> <span class="token operator">></span> <span class="token comment">#<Abc:0x0000000009c13a50 @ahaha=11></span> <span class="token punctuation">[</span> <span class="token number">2</span> <span class="token punctuation">]</span> <span class="token function">pry</span> <span class="token punctuation">(</span> main <span class="token punctuation">)</span> <span class="token operator">></span> <span class="token constant">Marshal</span> <span class="token punctuation">.</span> dump a <span class="token operator">=</span> <span class="token operator">></span> <span class="token string">"x04bo:bAbcx06: <a class="__cf_email__" href="/cdn-cgi/l/email-protection">[email protected]</a> x10"</span> <span class="token punctuation">[</span> <span class="token number">3</span> <span class="token punctuation">]</span> <span class="token function">pry</span> <span class="token punctuation">(</span> main <span class="token punctuation">)</span> <span class="token operator">></span> <span class="token constant">Marshal</span> <span class="token punctuation">.</span> <span class="token function">load</span> <span class="token punctuation">(</span> <span class="token constant">Marshal</span> <span class="token punctuation">.</span> <span class="token function">dump</span> <span class="token punctuation">(</span> a <span class="token punctuation">)</span> <span class="token punctuation">)</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token comment">#<Abc:0x0000000009e33510 @ahaha=11></span> <span class="token punctuation">[</span> <span class="token number">4</span> <span class="token punctuation">]</span> <span class="token function">pry</span> <span class="token punctuation">(</span> main <span class="token punctuation">)</span> <span class="token operator">></span> <span class="token constant">Marshal</span> <span class="token punctuation">.</span> <span class="token function">load</span> <span class="token punctuation">(</span> <span class="token string">"x04bo:bAbcx06: <a class="__cf_email__" href="/cdn-cgi/l/email-protection">[email protected]</a> x10"</span> <span class="token punctuation">)</span> <span class="token operator">=</span> <span class="token operator">></span> <span class="token comment">#<Abc:0x0000000009e85d10 @ahaha=11></span> |
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
1 2 3 4 5 6 | s <span class="token operator">=</span> <span class="token string">"untrusted"</span> s <span class="token punctuation">.</span> taint s <span class="token punctuation">.</span> tainted <span class="token operator">?</span> s <span class="token punctuation">.</span> upcase <span class="token punctuation">.</span> tainted <span class="token operator">?</span> s <span class="token punctuation">[</span> <span class="token number">3</span> <span class="token punctuation">,</span> <span class="token number">4</span> <span class="token punctuation">]</span> <span class="token punctuation">.</span> tainted <span class="token operator">?</span> |
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):
1 2 3 4 | a <span class="token operator">=</span> <span class="token number">0.0</span> <span class="token keyword">if</span> <span class="token keyword">false</span> <span class="token comment"># hành động gán này chả bao h xảy ra</span> print doc_co_cau_bai <span class="token comment"># ấy vậy mà chỗ này vẫn in ra `nil` =))</span> print dong_phuong_bat_bai <span class="token comment"># NameError: trong khi ở đây bắn lỗi như đúng rồi</span> |
=> 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 thatTê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 indo / end
pairs. Methods can execute code within this block by using theyield
keyword. This ability to arbitrarily associateblock 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 …