Menu
CoddyTech

三元运算符

本课属于 Coddy Ruby 学习旅程的“逻辑与流程”单元。第 40 课,共 56 课。

三元运算符是 if/else 的单行简写形式,可以返回一个值。语法为 condition ? value_if_true : value_if_false。

age = 20
status = age >= 18 ? "Eligible" : "Not Eligible"
puts status   # Eligible

这和写成下面这样是一样的:

status = if age >= 18
           "Eligible"
         else
           "Not Eligible"
         end

当两个分支都返回较短的值时,使用三元运算符。如果任一分支需要多个表达式,就改用普通的 if/else:在三元运算符中塞入太多内容会让代码难以阅读。

你可以直接在其他表达式中使用它,包括插值:

count = 1
puts "#{count} item#{count == 1 ? "" : "s"}"   # 1 个物品
count = 5
puts "#{count} item#{count == 1 ? "" : "s"}"   # 5 个物品
challenge icon

挑战

简单

从输入中读取一个整数 n。使用三元运算符(不使用 if/else 代码块),准确输出:

<n> is <label>

其中,label 的值为:

  • 当 n > 0 时为 positive
  • 当 n < 0 时为 negative
  • 当 n == 0 时为 zero

提示:使用嵌套三元运算符,condition ? a : (other_condition ? b : c)。

输入 5 时,输出为 5 is positive。输入 0 时,输出为 0 is zero。

亲手试试

n = gets.to_i

# TODO:用三元表达式生成标签,然后用 puts 输出。
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

逻辑与流程中的所有课

自己练习: Ruby 在线编译器