1.簡介
2.安裝
3.基本語法
4高級進階
1.簡介
Ruby是一個面向對象的腳本語言,由Yukihiro Matsumoto設計。它可以運行於各種平臺,Windows,Mac OS, 及各種Linux/Unix。
Ruby特點:
- 開源,授權
- 通用解釋性語言
- 面向對象
- 服務器端的腳本語言,和Python, Perl類似
- 可以來寫CGI(common gateway interface)
- 可以鑲嵌到HTML
- 簡單易學的語法
- 可擴展性好
- 支持許多GUI工具,譬如GTK,OpenGL等
- 很容易和DB2,Mysql,Oracle,Sybase 等數據庫連接
- 有好多內置函數可以直接使用
本教程所需
最小2G內存的機器。
-
Linux 或 Windows 系統
-
Apache Web server.
-
瀏覽器
-
Ruby
2.安裝
https://www.ruby-lang.org/en/documentation/installation/ 安裝文檔連接
https://www.ruby-lang.org/en/downloads/ 軟件下載鏈接
2.1.1 Linux/Unix 安裝 :
簡單命令安裝。安裝包,或編譯源碼方法此處省略。
apt (Debian or Ubuntu)
$ sudo apt-get install ruby-full
yum (CentOS, Fedora, or RHEL)
$ sudo yum install ruby
snap (Ubuntu or other Linux distributions)
$ sudo snap install ruby --classic
也可以制定安裝其他版本。
$ sudo snap switch ruby --channel=2.3/stable
$ sudo snap refresh
portage (Gentoo)
$ sudo emerge dev-lang/ruby
pacman (Arch Linux)
$ sudo pacman -S ruby
Homebrew (macOS)
$ brew install ruby
FreeBSD
$ pkg install ruby
我用的是irtualbox-Ubuntu18, 安裝完,執行命令 ruby -v. 返回版本,安裝成功。
zzl@zzl-VirtualBox:~$ ruby -v
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux-gnu]
2.1.2Windows 安裝 :
https://rubyinstaller.org/downloads/ Windows installer 下載鏈接。
根據需要,選擇需要的版本,然後安裝。installer安裝方式, 就不贅述了。
2.2Ruby 命令行選項 − 可以和Ruby解釋器一起使用.
格式如下
$ ruby [ options ] [.] [ programfile ] [ arguments ... ] 解釋器可以使用以下選項:
Sr.No. | 選項及描述 |
---|---|
1 |
-a 與 -n 或-p 一起使用來分割每行. 查看 -n 和 -p選項. |
2 |
-c 只檢查句法,不執行程序. |
3 |
-C dir 在執行前更改目錄(與 -X相同). |
4 |
-d 啓用debug模式 (與 -debug相同). |
5 |
-F pat 被split使用,指定pat作爲缺省分割模式 ($;) |
6 |
-e prog 指定prog作爲命令行程序。 多個程序,用多個 -e 選項. |
7 |
-h 顯示命令行選項概覽。 |
8 |
-i [ ext]
用程序輸出覆蓋文件內容。原始文件被保存爲.ext擴展文件。如果ext沒有指定,原始文件被刪除。 |
9 |
-I dir 加目錄添加爲載入庫。 |
10 |
-K [ kcode]
指定多字節字符集(e,E代表EUC(exttended Unix code); s,S代表SJIS(Shift-JIS); u, U 代表UTF8, a,A,n,或S代表ASCII。 |
11 |
-l
啓用行結束符自動處理。從輸入行截斷 newline,在輸出行附加newline. |
12 |
-n
在輸入循環內放置代碼(和在 while gets; ...end 類似) |
13 |
-0[ octal]
將默認記錄分隔符($/)設置爲八進制octal.默認爲\0,如果octal 沒有指定。 |
14 |
-p
在輸入循環內放置代碼。 爲每一次迭代寫 $_ |
15 |
-r lib 執行前,使用require 載入lib作爲庫使用。 |
16 |
-s 將程序名和文件並之間 匹配 -xxx的參數作爲開關,並定義相應的變量。 |
17 |
-T [level] 設置Tainting 檢查級別爲 level(默認爲1,如果沒有指定). |
18 |
-v 顯示版本,並啓用verbose模式。 |
19 |
-w 啓用 warning。 |
20 |
-x [dir] 剝離 #!ruby 行前的文本.如果dir指定,則執行前將目錄更換到dir |
21 |
-X dir 執行前改變目錄。 (與 -C相同). |
22 |
-y 啓用Parser debug 模式。. |
23 |
--copyright 顯示版權信息. |
24 |
--debug 啓用debug 模式 (與 -d相同). |
25 |
--help 顯示命令行選項幫助 (與-h 相同). |
26 |
--version 顯示版本 . |
27 |
--verbose 啓用 verbose 模式(與 -v相同). 將 $VERBOSE 設置爲 true. |
28 |
--yydebug 啓用parser debug 模式。 (與 -y 相同). |
多個單字符選項可以合併,例如下面倆個命令作用等同。
$ruby -ne 'print if /Ruby/' /usr/share/bin $ruby -n -e 'print if /Ruby/' /usr/share/bin
2.3Ruby 環境變量
Sr.No. | 變量及描述 |
---|---|
1 |
DLN_LIBRARY_PATH 動態載入模塊路徑 |
2 |
HOME
當沒有參數傳給Dir::chdir時,使用的目錄。File::expand_path 來展開“~” |
3 |
LOGDIR
當沒有參數傳給Dir::chdir時,並且HOME沒有設置,使用的目錄。 |
4 |
PATH
執行子進程搜尋的路徑,和使用-S選項來搜索Ruby程序的路徑。 |
5 |
RUBYLIB Search path for libraries. Separate each path with a colon (semicolon in DOS and Windows). 庫路徑。以:冒號分開(window下用: 分號) |
6 |
RUBYLIB_PREFIX 用來修改RUBYLIB搜索路徑,通過path1;path2或 path1path2格式將prefix path1替換爲path2. |
7 |
RUBYOPT 傳給Ruby解釋器的命令行選項。taint 模式下被忽略。($SAFE大於0) |
8 |
RUBYPATH 使用-S選項,來搜查Ruby 程序。 優先級高於PATH。 taint 模式下被忽略($SAFE大於0)。 |
9 |
RUBYSHELL 爲派生的進程指定的SHELL。如果沒有設置,檢查SHELL或COMSPEC。 |
Unix/linux, 可以查看.env文件查看環境變量。
編輯器:
ubuntu 18 下我用nano. 也安裝了Visual Studio Code。 任何你順手的編輯器都可以。
Interactive Ruby (IRb) 交互Ruby:
安裝Ruby的時候,這個工具就附帶安裝了。只需要在命令行窗口鍵入irb,並enter。
zzl@zzl-VirtualBox:~$ irb
irb(main):001:0> def hello
irb(main):002:1> out ="hello, Ruby!"
irb(main):003:1> puts out
irb(main):004:1> end
=> :hello
irb(main):005:0> hello
hello, Ruby!
=> nil
irb(main):006:0>
3.基本語法
3.1句法syntax
Ruby程序文件以rb結束。將puts "Hello, World!";保存到test.rb中。查看文件,然後執行。
zzl@zzl-VirtualBox:~/rubyprojects$ cat test.rb
puts "Hello, World!";
zzl@zzl-VirtualBox:~/rubyprojects$ ruby test.rb
Hello, World!
zzl@zzl-VirtualBox:~/rubyprojects$
空白符,一般被忽略,除非他們出現在字符串中。
Ruby將分號(;)和新行(\n)作爲結束。 不過在行末遇到操作符時,例如+,-, /等,表示語句繼續。
標識符是變量,常量及方法的名字。 區分大小寫,可以由字母字符和下劃線組成。
Reserved Words保留字
保留字不能用作常量或變量名字,但是可以做方法名字。
BEGIN | do | next | then |
END | else | nil | true |
alias | elsif | not | undef |
and | end | or | unless |
begin | ensure | redo | until |
break | false | rescue | when |
case | for | retry | while |
class | if | return | while |
def | in | self | __FILE__ |
defined? | module | super | __LINE__ |
Here Document in Ruby
"Here Document" 指用多行來組建字符串. 在 <<後,你可以指定一個字符串或標識符來結束字符串,當前行之後一直到結束符,就是字符串的值。如果結束符被引用,引號的類型決定了字符串的類型。注意, <<和結束符直接沒有空白。
編輯一個Ruby文件,寫入以下內容: print <<EOF This is the first way of creating here document ie. multiple line string. EOF print <<"EOF"; # same as above This is the second way of creating here document ie. multiple line string. EOF print <<`EOC` # execute commands echo "hi there" echo "lo there" EOC print <<"foo", <<"bar" # you can stack them I said foo. foo I said bar. 然後執行這個文件: zzl@zzl-VirtualBox:~/rubyprojects$ ruby demo_heredoc.rb This is the first way of creating here document ie. multiple line string. This is the second way of creating here document ie. multiple line string. hi there lo there I said foo. I said bar. zzl@zzl-VirtualBox:~/rubyprojects$
Ruby BEGIN Statement
BEGIN { code }
聲明在程序執行前執行的代碼
Ruby END Statement
END { code }
聲明在程序執行後執行的代碼。
編寫一個示例程序demo_beginend.rb,輸入以下內容:
puts "This is the main Ruby Program" END { puts "Terminating Ruby Program" } BEGIN { puts "Initializing Ruby Program" }
執行結果:
zzl@zzl-VirtualBox:~/rubyprojects$ ruby demo_beginend.rb
Initializing Ruby Program
This is the main Ruby Program
Terminating Ruby Program
zzl@zzl-VirtualBox:~/rubyprojects$
Ruby Comments 註釋
在開頭用#註釋,
# I am a comment. Just ignore me.
在語句末尾註釋
name = "Madisetti" # This is again comment
註釋多行
# This is a comment. # This is a comment, 2. # This is a comment, 3.
用=begin/=end組合來註釋多行或塊:
=begin This is a comment. This is a comment, too. This is a comment, too. I said that already. =end
3.2Classes and Objects 類和對象
Ruby 是面向對象的編程語言。面向對象包括:
- Data Encapsulation 數據封包
- Data Abstraction 數據抽象
- Polymorphism 多態
- Inheritance 繼承
面向對象的程序與類和對象相關。類是創建對象的藍本。
Defining a Class in Ruby Ruby定義類
以class 關鍵詞開始,然後是類的名字,類名字首字母要大寫,以關鍵詞end結束。class Customer 如此定義:
class Customer end
Variables in a Ruby Class 類變量
變量類型
-
Local Variables −局部變量是方法中定義。在方法外不是變量。 用小寫字母或_開頭。
-
Instance Variables − 實例變量是跨方法可以使用的。不同對象的實例變量不同。實例變量以@開頭後面是變量名字。I
-
Class Variables − 類變量是跨對象可以使用的。類變量屬於類,是類的一個特性。以@@開頭,後面是變量名字。
-
Global Variables − 類變量跨類不可使用。要跨類使用,需要定義全局變量。全局變量以$開頭。
示例
類變量 @@no_of_customers, 你可確定創建對象的個數。也可以推導customers個數。
class Customer @@no_of_customers = 0 end
Creating Objects in Ruby using new Method 使用new 方式創建對象
對象是類的實例。可以用new方式來創建對象。
new 方法是Ruby庫預定義的,屬於類方法。
創建cust1和cust2對象:
cust1 = Customer.new cust2 = Customer.new
Custom Method to Create Ruby Objects 自定義創建Ruby對象方法
可以給new方法傳參數,這些參數可以來初始化類變量。Y
創建類的時候需要聲明initialize方法,如果你要給new方法傳參數的話。
The initialize method is a special type of method, which will be executed when the new method of the class is called with parameters. initalize 方法是特殊類型的方法,當類的new方法被傳參調用時會執行。
舉例:
class Customer @@no_of_customers = 0 def initialize(id, name, addr) @cust_id = id @cust_name = name @cust_addr = addr end end
本例定義 initialize 方法, id, name,和addr 作爲局部變量.def 和 end 定義方法 initialize.
創建對象:
cust1 = Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2 = Customer.new("2", "Poul", "New Empire road, Khandala")
Member Functions in Ruby Class 成員函數
Ruby中,函數被叫住方法。每個方法以def 開頭,然後是方法名字,中間是語句,以end結束。
方法名字最好用小寫字母。
格式如下
class Sample def function statement 1 statement 2 end end
舉例,在irb中輸入:
class Sample def hello puts "Hello Ruby!" end end # Now using above class to create objects object = Sample. new
結果如下:
irb(main):007:0> object.hello Hello Ruby!
3.3 Ruby-Variable 變量舉例
3.3.1全局變量
以$開頭。
$global_variable = 10 class Class1 def print_global puts "Global variable in Class1 is #$global_variable" end end class Class2 def print_global puts "Global variable in Class2 is #$global_variable" end end class1obj = Class1.new class1obj.print_global class2obj = Class2.new class2obj.print_global
結果如下:
Global variable in Class1 is 10
Global variable in Class2 is 10
3.3.2實例變量
以 @開頭。
class Customer def initialize(id, name, addr) @cust_id = id @cust_name = name @cust_addr = addr end def display_details() puts "Customer id #@cust_id" puts "Customer name #@cust_name" puts "Customer address #@cust_addr" end end # Create Objects cust1 = Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2 = Customer.new("2", "Poul", "New Empire road, Khandala") 調用方法,結果: irb(main):042:0> cust1.display_details() Customer id 1 Customer name John Customer address Wisdom Apartments, Ludhiya => nil irb(main):043:0> cust2.display_details() Customer id 2 Customer name Poul Customer address New Empire road, Khandala => nil
3.3.3類變量
類變量以 @@開頭,在方法定義使用前必須初始化。類變量被類後代或類變量所定義的模塊共享。
class Customer @@no_of_customers = 0 def initialize(id, name, addr) @cust_id = id @cust_name = name @cust_addr = addr end def display_details() puts "Customer id #@cust_id" puts "Customer name #@cust_name" puts "Customer address #@cust_addr" end def total_no_of_customers() @@no_of_customers += 1 puts "Total number of customers: #@@no_of_customers" end end # Create Objects cust1 = Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2 = Customer.new("2", "Poul", "New Empire road, Khandala") 調用cust1.total_no_of_customers()和 cust2.total_no_of_customers(),結果如下:
irb(main):064:0> cust1.total_no_of_customers()
Total number of customers: 1
=> nil
irb(main):065:0> cust2.total_no_of_customers()
Total number of customers: 2
=> nil
3.3.4 局部變量
局部變量小寫或 _開頭. 局部變量的範圍取決於定義它的類,模塊,def, 或 do 到相應的end ,或一個語句塊{}.
3.3.5 常量
常量以大寫開頭。常量定義在類,模塊內,在類或模塊內可以被訪問; 或者定義在類或方法外,可以被全局訪問。
常量不能定義在方法內。
3.3.6 假變量
-
self − The receiver object of the current method.
-
true − Value representing true.
-
false − Value representing false.
-
nil − Value representing undefined.
-
__FILE__ − The name of the current source file.
-
__LINE__ − The current line number in the source file.
3.3.7 基本類型
Integer Numbers整數
Floating Numbers浮點數
String 字符串
Backslash Notations 轉義符
Notation | Character represented |
---|---|
\n | Newline (0x0a) |
\r | Carriage return (0x0d) |
\f | Formfeed (0x0c) |
\b | Backspace (0x08) |
\a | Bell (0x07) |
\e | Escape (0x1b) |
\s | Space (0x20) |
\nnn | Octal notation (n being 0-7) |
\xnn | Hexadecimal notation (n being 0-9, a-f, or A-F) |
\cx, \C-x | Control-x |
\M-x | Meta-x (c | 0x80) |
\M-\C-x | Meta-Control-x |
\x | Character x |
Arrays數組
Ruby Hashes
在{}內存放鍵值對key/value pairs列表就是Ruby Hash.,鍵值直接用,或 => 分割。
Ruby Ranges 範圍
範圍用 s..e 和 s...e , 或 with Range.new來構造。
(1..5) 包括1, 2, 3, 4, 5 (1...5) 包括 1, 2, 3, 4 。