Ruby逻辑运算符 #

一、逻辑运算符概述 #

Ruby提供了多种逻辑运算符,用于组合和操作布尔值。

运算符 描述 示例
&& true && false
|| true || false
! !true
and true and false
or true or false
not not true

二、与运算 #

2.1 && 运算符 #

ruby
true && true
true && false
false && true
false && false

2.2 and 运算符 #

ruby
true and true
true and false
false and true
false and false

2.3 && vs and #

ruby
a = true && false
a = true and false

2.4 短路求值 #

ruby
def expensive
  puts "执行"
  true
end

false && expensive
true && expensive

nil && expensive

三、或运算 #

3.1 || 运算符 #

ruby
true || true
true || false
false || true
false || false

3.2 or 运算符 #

ruby
true or true
true or false
false or true
false or false

3.3 || vs or #

ruby
a = false || true
a = false or true

3.4 短路求值 #

ruby
def expensive
  puts "执行"
  true
end

true || expensive
false || expensive

nil || expensive

四、非运算 #

4.1 ! 运算符 #

ruby
!true
!false
!nil
!!true
!!false
!!nil
!!0
!!""

4.2 not 运算符 #

ruby
not true
not false
not nil

4.3 ! vs not #

ruby
!true && false
not true && false

五、运算符优先级 #

5.1 优先级表 #

ruby
!true && false
!true || false
true && false || true
true || false && false

5.2 && vs and 优先级 #

ruby
a = true && false
a = true and false

b = false || true
b = false or true

5.3 推荐用法 #

ruby
success = a && b && c

result = operation or raise "失败"

if a && b
  puts "success"
end

六、真假值规则 #

6.1 Ruby的真假值 #

ruby
!nil
!false
!true
!0
!""
![]
!{}

6.2 双重否定 #

ruby
def truthy?(value)
  !!value
end

truthy?(1)
truthy?("")
truthy?(nil)
truthy?(false)

七、实用模式 #

7.1 默认值 #

ruby
name = nil
name = name || "Guest"
name ||= "Guest"

config = {}
config[:timeout] ||= 30
config[:timeout] ||= 60

7.2 条件赋值 #

ruby
user = find_user(id) || create_guest

result = operation || default_value

7.3 存在性检查 #

ruby
def process(data)
  return unless data

  puts "处理: #{data}"
end

def greet(name = nil)
  name ||= "Guest"
  puts "Hello, #{name}"
end

7.4 链式检查 #

ruby
if user && user.profile && user.profile.avatar
  puts user.profile.avatar
end

if user&.profile&.avatar
  puts user&.profile&.avatar
end

八、条件表达式 #

8.1 三元运算符 #

ruby
age = 20
status = age >= 18 ? "成年" : "未成年"

result = condition ? "真" : "假"

8.2 条件修饰符 #

ruby
admin = true
puts "欢迎管理员" if admin
puts "请登录" unless logged_in

8.3 复合条件 #

ruby
if logged_in? && admin?
  puts "管理员页面"
end

if guest? || expired?
  puts "请登录"
end

unless valid? && authorized?
  raise "访问被拒绝"
end

九、逻辑运算方法 #

9.1 方法形式 #

ruby
true.send(:&&, false)
false.send(:||, true)
true.send(:!)

9.2 自定义逻辑 #

ruby
class TriState
  TRUE = :true
  FALSE = :false
  MAYBE = :maybe

  attr_reader :value

  def initialize(value)
    @value = value
  end

  def and(other)
    case [value, other.value]
    when [TRUE, TRUE] then TriState.new(TRUE)
    when [FALSE, _], [_, FALSE] then TriState.new(FALSE)
    else TriState.new(MAYBE)
    end
  end

  def or(other)
    case [value, other.value]
    when [TRUE, _], [_, TRUE] then TriState.new(TRUE)
    when [FALSE, FALSE] then TriState.new(FALSE)
    else TriState.new(MAYBE)
    end
  end

  def not
    case value
    when TRUE then TriState.new(FALSE)
    when FALSE then TriState.new(TRUE)
    else TriState.new(MAYBE)
    end
  end
end

十、实用示例 #

10.1 权限检查 #

ruby
def can_edit?(user, post)
  user.admin? || (user == post.author && post.published?)
end

def can_delete?(user, post)
  user.admin? || user == post.author
end

10.2 配置默认值 #

ruby
class Config
  def initialize(options = {})
    @host = options[:host] || "localhost"
    @port = options[:port] || 3000
    @timeout = options[:timeout] || 30
    @debug = options[:debug] || false
  end
end

config = Config.new(host: "example.com")

10.3 验证器 #

ruby
class Validator
  def self.valid?(data)
    data &&
      data[:name] && !data[:name].empty? &&
      data[:email] && data[:email].match?(/@/) &&
      data[:age] && data[:age] > 0
  end
end

Validator.valid?({ name: "Ruby", email: "ruby@example.com", age: 30 })
Validator.valid?({ name: "", email: "invalid", age: -1 })

10.4 安全导航链 #

ruby
def get_user_avatar(user)
  user&.profile&.avatar&.url || "default.png"
end

def get_nested_value(hash, *keys)
  keys.reduce(hash) { |h, k| h&.[](k) }
end

10.5 条件执行 #

ruby
def save(data)
  valid?(data) && persist(data) && notify(data)
end

def process(items)
  items.any? && process_all(items)
end

十一、最佳实践 #

11.1 使用 && 和 || #

ruby
if a && b
  do_something
end

result = a || b

11.2 and 和 or 用于流程控制 #

ruby
save && redirect or render(:new)

copy_file or raise "复制失败"

11.3 避免复杂表达式 #

ruby
if (user.admin? || user.moderator?) && post.published? && !post.locked?
  allow_edit
end

def can_edit?
  (admin? || moderator?) && published? && !locked?
end

if can_edit?
  allow_edit
end

十二、总结 #

本章我们学习了:

  1. 与运算:&&、and、短路求值
  2. 或运算:||、or、短路求值
  3. 非运算:!、not、双重否定
  4. 优先级:&& > || > and > or
  5. 实用模式:默认值、条件赋值、存在性检查
  6. 最佳实践:&&/||用于布尔运算,and/or用于流程控制

接下来让我们学习Ruby的位运算符!

最后更新:2026-03-27