Footprint

We walk and learn


Project maintained by cellzero Hosted on GitHub Pages — Theme by mattgraham

读书笔记:Ruby基础教程第5版

Ruby version: 2.3.0

CH-05 条件判断


真假值


逻辑运算符


基本语法

if语句

条件为真时执行处理。

if cond_1 then
  handle_1
elsif cond_2 then
  handle_2
else
  handle_3
end

unless语句

条件为假时执行处理,没有 elsif 写法。

unless cond_1 then
  handle_false
else
  handle_true
end

case语句

该语句在判断是否相等时,使用 === 运算符来判断。除了数值上的相等,还可以判断正则表达式是否匹配,对象是否属于类,等等。

/zz/ === "xyzzy"    # => true
String === "xyzzy"  # => true
(1 .. 3) === 2      # => true

该语句一次可以比较多个值。其具体语法如下:

case cmp_obj
when value then
  handle
else
  default
end

一些有趣的例子。

tags = ["A", "IMG", "PRE"]
tags.each do |tagname|
  case tagname
  when "P", "A", "B"
    puts "#{tagname} has child."
  when "IMG", "BR"
    puts "#{tagname} has no child."
  else
    puts "#{tagname} cannot be used."
  end
end
ary = ["a", 1, nil]
ary.each do |item|
  case item
  when String
    puts "#{item} is a String."
  when Numeric
    puts "#{item} is a Numeric."
  else
    puts "#{item} is something."
  end
end
text.each_line do |line|
  case line
  when /^From:/i
    puts "Sender"
  when /^To:/i
    puts "Receiver"
  when /^$/
    puts "End"
  else
    # nothing to do
  end
end

修饰符

handle_true if cond_true
handle_false unless cond_false

对象同一性

对象的标识(ID)可以通过 object_id__id__ 方法获得。可以使用 equal? 方法判断是否为同一对象。

可以使用 == 判断对象的值是否相等,此方法定义在 Object 类中。

同样定义在 Object 类中的方法 eql? 在值相等的基础上,还会考察类型。散列即使用 eql? 方法来判断不同的键。

str1 = "foo"
str2 = str1
str3 = "foo"

str1 == str2       # => true
str1 == str3       # => true

str1.equal?(str2)  # => true
str1.equal?(str3)  # => false

1.0 == 1           # => true
1.0.eql?(1)        # => false

Back