如何在Ruby中编写switch语句?
当前回答
你可以用更自然的方式这样做,
case expression
when condtion1
function
when condition2
function
else
function
end
其他回答
案例什么时候
为Chuck的答案添加更多示例:
使用参数:
case a
when 1
puts "Single value"
when 2, 3
puts "One of comma-separated values"
when 4..6
puts "One of 4, 5, 6"
when 7...9
puts "One of 7, 8, but not 9"
else
puts "Any other thing"
end
无参数:
case
when b < 3
puts "Little than 3"
when b == 3
puts "Equal to 3"
when (1..10) === b
puts "Something in closed range of [1..10]"
end
请注意kikito警告的“如何在Ruby中编写switch语句”。
很多很好的答案,但我想我会补充一个事实。。如果您试图比较对象(类),请确保您有一个太空船方法(不是玩笑)或了解它们是如何比较的
“Ruby平等和对象比较”是一个很好的话题讨论。
$age = 5
case $age
when 0 .. 2
puts "baby"
when 3 .. 6
puts "little child"
when 7 .. 12
puts "child"
when 13 .. 18
puts "youth"
else
puts "adult"
end
有关更多信息,请参阅“Ruby-if…else,case,除非”。
case语句运算符在其他语言中类似于switch。
这是switch的语法。。。C中的情况:
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
这是case的语法。。。使用Ruby时:
case expression
when constant1, constant2 #Each when statement can have multiple candidate values, separated by commas.
# statements
next # is like continue in other languages
when constant3
# statements
exit # exit is like break in other languages
.
.
.
else
# statements
end
例如:
x = 10
case x
when 1,2,3
puts "1, 2, or 3"
exit
when 10
puts "10" # it will stop here and execute that line
exit # then it'll exit
else
puts "Some other number"
end
有关更多信息,请参阅案例文档。
如果您渴望知道如何在Ruby开关情况下使用OR条件:
因此,在case语句中,a相当于if语句中的||。
case car
when 'Maruti', 'Hyundai'
# Code here
end
请参阅“Ruby Case语句的工作原理和使用它可以做什么”。
推荐文章
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- 有效,但毫无价值的语法在开关情况下?
- 最好的打印散列的方法
- Rails:dependent =>:destroy VS:dependent =>:delete_all
- 我可以在不包含Ruby模块的情况下调用实例方法吗?
- 如何将新项目添加到哈希
- 测试一个Ruby类是否是另一个类的子类
- 什么时候使用Struct vs. OpenStruct?
- 数组到哈希Ruby
- 我如何让红宝石打印一个完整的回溯而不是截断一个?
- 如何使用RSpec的should_raise与任何类型的异常?
- 如何创建退出消息
- 忽略GEM,因为没有构建它的扩展
- 在Gem::Specification.reset期间未解决的规格:
- Delete_all vs destroy_all