Ruby 简明教程 Part 1

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保留字

保留字不能用作常量或变量名字,但是可以做方法名字。

BEGINdonextthen
ENDelseniltrue
aliaselsifnotundef
andendorunless
beginensureredountil
breakfalserescuewhen
caseforretrywhile
classifreturnwhile
definself__FILE__
defined?modulesuper__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 转义符

NotationCharacter represented
\nNewline (0x0a)
\rCarriage return (0x0d)
\fFormfeed (0x0c)
\bBackspace (0x08)
\aBell (0x07)
\eEscape (0x1b)
\sSpace (0x20)
\nnnOctal notation (n being 0-7)
\xnnHexadecimal notation (n being 0-9, a-f, or A-F)
\cx, \C-xControl-x
\M-xMeta-x (c | 0x80)
\M-\C-xMeta-Control-x
\xCharacter 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 。

 

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值