操作符 #
常用操作符 #
数学计算不支持 ++
操作
puts 3 + 2 < 5 -7 # => false
x = 10
x += 1
puts x # => 11
puts(2 ** 3) # => 8
puts(9 / 3) # => 3
逻辑操作
puts true and 1 == 2 # => true
puts true && 1 == 2 # => false
puts true or 1 == 2 # => true
puts true || 1 == 2 # => true
puts !true # => false
puts (not (1==1)) # => false
puts 3 > 2 ? '3>2' : '3<=2' # => 3>2
条件赋值
参数为空时进行赋值
favorite_book ||= "Cat's Cradle"
相等性 #
==
比较的是内容
puts 1 == 1 # => true
puts 1 != 2 # => true
puts "foo" == "foo" # => true
比较数字
puts 1 == 1.0 # => true
puts 1.eql? 1.0 # => false
比较对象
foo = 'foo'
foo_dup = foo.dup
puts foo == foo_dup # => true
puts foo.equal? foo_dup # => false
比较器 #
比较器返回的是整形数字,使用符号 <==>
book_1 = 'A Wrinkle in Time'
book_2 = 'A Brief History of Time'
puts book_1 <=> book_2 # => 1
比较器可以用在排序中
books = ['Charlie and the Chocolate Factory', 'War and Peace', 'Utopia', 'A Brief History of Time', 'A Wrinkle in Time']
puts books.sort! { |firstBook, secondBook| firstBook <=> secondBook }
defined? #
defined?
用于判断一个变量或函数是否被定义,如果定义了则返回对应的描述字符串(如 local variable, global variable),否则返回空。
puts defined? foo # => local-variable
puts defined? puts # => method
BEGIN 与 END #
BEGIN 与 END 可以用于定义在程序运行前后执行的代码块,即实现 hook 功能。
BEGIN {
puts 'setUp'
}
END {
puts 'tearDown'
}
BEGIN 与 END 可以定义多个,BEGIN 按照定义的顺序执行,END 则相反,定义在后面的先执行。
BEGIN {
puts 'setUp01'
}
BEGIN {
puts 'setUp02'
}
BEGIN {
puts 'setUp03'
}
END {
puts 'tearDown01'
}
END {
puts 'tearDown02'
}
END {
puts 'tearDown03'
}
以上代码会输出
setUp01
setUp02
setUp03
tearDown03
tearDown02
tearDown01