“Ruby is simple in appearance, but is very complex inside, just like our human body.” — Matz, creator of the Ruby programming language
前言
先纵览一下整体 Ruby 的语法,粗略的读一下在线教程 《ruby基础教程(中文第四版)》,如果连接失效,可以到 链接: https://pan.baidu.com/s/1TUeRBYz0e7RqmauTftqXhA 密码: 2qpk 下载 epub(注:为了分享学习使用,若侵即删)
交互式 ruby 界面
# > ruby -E UTF-8 脚本文件名 ← 脚本执行
# > irb -E UTF-8 ← irb 启动
# > irb --simple-prompt 简化输出
打印
print("Hello, Ruby.\n") #=>Hello, Ruby.
print('Hello, \nRuby\n!\n') #=>Hello, \nRuby\n!\n
print("Hello, \nRuby\n!\n") #=>Hello, #换行# Ruby
puts "Hello, ", "Ruby" #=>Hello, #换行# Ruby
puts "100" #=> 100
puts 100 #=> 100
p "100" #=> "100"
p 100 #=> 100
puts "Hello, \n\tRuby." #=> 转义
p "Hello, \n\tRuby." #=> 不转义
print "表面积=", (20 * 2), "\n"
print "表面积=#{20 * 2}\n"
注释
# 这是一个单行注释。
=begin
我是多行注释
哦
=end
变量
定义一个变量,存储 1
one = 1
除了定义 integer ,还可以定义 String,boolean,symbol,float 等等
t_val = true
f_val = false
name = "Grac Kanil"
symbol = :symbol
price = 11.25
# 局部变量以英文字母或者 _ 开头。
# 全局变量以 $ 开头。
# 实例变量以 @ 开头。
# 类变量以 @@ 开头
常量
# 常量
> irb --simple-prompt
>> TEST = 1
=> 1
>> TEST = 2
(irb):4: warning: already initialized constant TEST
(irb):3: warning: previous definition of TEST was here
=> 2
赋值
a, b, c = 1, 2, 3
a, b, c, d = 1, 2
p [a, b, c] #=> [1, 2, nil]
a, b, *c = 1, 2, 3, 4, 5
p [a, b, c] #=> [1, 2, [3, 4, 5]]
a, * b, c = 1, 2, 3, 4, 5
p [a, b, c] #-> [1, [2, 3, 4], 5]
a, b = 0, 1
a, b = b, a # 置换变量a、b 的值
p [a, b] #=> [1, 0
ary = [1, 2]
a, b = ary
p a #=> 1
p b #=> 2
ary = [1, [2, 3], 4]
a, b, c = ary
p a #=> 1
p b #=> [2, 3]
p c #=> 4
ary = [1, [2, 3], 4]
a, (b1, b2), c = ary # 对与数组结构相对应的变量赋值
p a #=> 1
p b1 #=> 2
p b2 #=> 3
p c #=> 4
控制流
# Ruby 会认为 false 与 nil 代表假,除此以外的所有值都代表真
# then 可以省略
x = 2
if x == 2 then
p "x=2"
end
if true
puts "Hello Ruby."
end
if 2 > 1
puts "bigger"
end
if 1 > 2
puts "bigger"
else
puts "smaller"
end
if 1 > 2
puts "bigger"
elsif 2 > 1
puts "smaller"
else
puts "equal"
end
if 条件 then
 处理
end
if 条件 1 then
 处理 1
elsif 条件 2 then
 处理 2
elsif 条件 3 then
 处理 3
else
 处理 4
end
unless 条件 then
 处理
end
unless 条件
 处理 1
else
 处理 2
end
if 条件
 处理 2
else
 处理 1
end
case 比较对象
when 值 1 then
 处理 1
when 值 2 then
 处理 2
when 值 3 then
 处理 3
else
 处理 4
end
def function?
true
end
# 方法名为 function?,问号表示返回 boolean 类型
puts "let’s go" if function?
循环和迭代
Ruby 中的迭代有许多种不同的形式,简单说一下 while,for 和 each。
循环次数.times do
 希望循环的处理
end
循环次数.times {
 希望循环的处理
}
for 变量 in 开始时的数值..结束时的数值 do
 希望循环的处理
end
for 变量 in 对象 do
 希望循环的处理
end
while 条件 do
 希望循环的处理
end
until 条件 do
 希望循环的处理
end
对象.each do | 变量 |
 希望循环的处理
end
对象.each {| 变量 |
 希望循环的处理
}
# do 也可以省略
i = 1
while i < 10 do
p "#{i}"
i = i + 1
end
n = 1
while n <= 10
puts n
n += 1
end
for n in 1....10
puts n
end
[1,2,3,4,5,6].each do |x|
puts x
end
each 和 loop 又有些区别,each 迭代器仅仅保持变量在 block 中,而 loop 允许变量在 block 外,如
irb --simple-prompt 中测试
?> for num in 1...5
>> puts num
>> end
1
2
3
4
=> 1...5
>> puts num
4
=> nil
然而
>> [1,2,3,4,5].each do |n|
?> puts n
>> end
1
2
3
4
5
=> [1, 2, 3, 4, 5]
>> puts n
NameError: undefined local variable or method `n' for main:Object
from (irb):17
from /Users/gekang/.rvm/rubies/ruby-2.2.4/bin/irb:11:in `<main>'
>>
另外也有无限循环的写法
loop do
print "Ruby"
end
集合
- array,众所周知,使用 index 可以操作 array,在 Ruby 中还有一些其他不同的操作方式,如
push和<<。
?> array = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
?> array = []
=> []
>> array.push("grac")
=> ["grac"]
>> array.push("kanil")
=> ["grac", "kanil"]
>>
?>
?> print array[0]
grac=> nil
>>
?> array = []
=> []
>> array << "Grac"
=> ["Grac"]
>> array << "Kanil"
=> ["Grac", "Kanil"]
也可以使用点语法,酷不酷?
?> array.<<("Ruby is cool,huh?")
=> ["Grac", "Kanil", "Ruby is cool,huh?"]
- hash,key-value 集合
?> hash = {
?> "key1" => "value1",
?> "key2" => "value2"
>> }
=> {"key1"=>"value1", "key2"=>"value2"}
可以使用任意类型作为 value
>> hash = {
?> "name" => "grackanil",
?> "age" => 20
>> }
=> {"name"=>"grackanil", "age"=>20}
hash["gender"] = "male"
- 迭代器在集合中的使用
?> array.each do |name|
?> puts name
>> end
grac
kanil
=> ["grac", "kanil"]
?> hash.each do |property, value|
?> puts "#{property}: #{value}"
>> end
name: grackanil
age: 20
gender: male
=> {"name"=>"grackanil", "age"=>20, "gender"=>"male"}
类和对象
面向对象语言,自然少不了类和对象的概念
class Animal
def initialize(species,habit)
@species = species
@habit = habit
end
end
cat = Animal.new("feline","meow")
- attr_reader(自动生成getter)
- attr_writer(自动生成setter)
- attr_accessor(自动生成 getter 和 setter)
提出 getter 和 setter 的概念,主要是体现一个封装的设计原则。
继承
class Cat < Animal
end
模块(一个工具箱)
包含一些常量和方法的集合
?> module Hi
>> def hello_world
>> puts "Hello, world."
>> end
>> end
=> :hello_world
?> class Test
>> include Hi
>> def initialize(user)
>> @user = user
>> end
>> end
=> :initialize
>> test = Test.new("grackanil")
=> #<Test:0x007fa01d801af0 @user="grackanil">
>> test.hello_world
Hello, world.
=> nil
module Tools
def class_name
p self
end
# module_function :class_name
end
class Son
include Tools
end
son = Son.new
if Son.include?(Tools)
son.class_name
end
p Son.ancestors
p Son.superclass
后语
可以说及其粗略地过了下 Ruby,但快乐之意,不会因为少而泛削减丝毫,大抵这就是魅力吧 :)
路漫漫其修远兮,吾将上下而求索。