如何在Ruby中编写switch语句?
当前回答
我更喜欢使用case+then
number = 10
case number
when 1...8 then # ...
when 8...15 then # ...
when 15.. then # ...
end
其他回答
根据您的情况,您可能更喜欢使用方法散列。
如果有一个很长的时间列表,并且每个时间都有一个具体的值可以比较(而不是一个间隔),那么声明一个方法散列,然后从散列中调用相关的方法会更有效。
# Define the hash
menu = {a: :menu1, b: :menu2, c: :menu2, d: :menu3}
# Define the methods
def menu1
puts 'menu 1'
end
def menu2
puts 'menu 2'
end
def menu3
puts 'menu3'
end
# Let's say we case by selected_menu = :a
selected_menu = :a
# Then just call the relevant method from the hash
send(menu[selected_menu])
Ruby使用case编写switch语句。
根据案例文件:
Case语句包含一个可选条件,该条件位于一个参数到case的位置,以及零个或多个when子句。与条件匹配的第一个when子句(或计算为布尔真值(如果条件为空)“wins”及其代码节执行。case语句的值是成功的when子句,如果没有这样的子句,则为nil。case语句可以以else子句结尾。当语句可以有多个候选值,用逗号分隔。
例子:
case x
when 1,2,3
puts "1, 2, or 3"
when 10
puts "10"
else
puts "Some other number"
end
较短版本:
case x
when 1,2,3 then puts "1, 2, or 3"
when 10 then puts "10"
else puts "Some other number"
end
正如“Ruby的case语句-高级技术”所描述的Ruby case;
可用于范围:
case 5
when (1..10)
puts "case statements match inclusion in a range"
end
## => "case statements match inclusion in a range"
可与Regex一起使用:
case "FOOBAR"
when /BAR$/
puts "they can match regular expressions!"
end
## => "they can match regular expressions!"
可与Procs和Lambdas一起使用:
case 40
when -> (n) { n.to_s == "40" }
puts "lambdas!"
end
## => "lambdas"
此外,还可以与您自己的匹配类一起使用:
class Success
def self.===(item)
item.status >= 200 && item.status < 300
end
end
class Empty
def self.===(item)
item.response_size == 0
end
end
case http_response
when Empty
puts "response was empty"
when Success
puts "response was a success"
end
很多很好的答案,但我想我会补充一个事实。。如果您试图比较对象(类),请确保您有一个太空船方法(不是玩笑)或了解它们是如何比较的
“Ruby平等和对象比较”是一个很好的话题讨论。
Ruby改用case表达式。
case x
when 1..5
"It's between 1 and 5"
when 6
"It's 6"
when "foo", "bar"
"It's either foo or bar"
when String
"You passed a string"
else
"You gave me #{x} -- I have no idea what to do with that."
end
Ruby使用==运算符将when子句中的对象与case子句中的目标进行比较。例如,1..5==x,而不是x===1..5。
这就允许出现上述复杂的when子句。范围、类别和所有种类的东西都可以测试,而不仅仅是平等。
与许多其他语言中的switch语句不同,Ruby的case没有中断,因此不需要在每次中断时结束。您还可以在一个when子句中指定多个匹配项,如when“foo”、“bar”。
你可以用更自然的方式这样做,
case expression
when condtion1
function
when condition2
function
else
function
end
推荐文章
- 了解Gemfile。锁文件
- 如何确定一个数组是否包含另一个数组的所有元素
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- 有效,但毫无价值的语法在开关情况下?
- 最好的打印散列的方法
- Rails:dependent =>:destroy VS:dependent =>:delete_all
- 我可以在不包含Ruby模块的情况下调用实例方法吗?
- 如何将新项目添加到哈希
- 测试一个Ruby类是否是另一个类的子类
- 什么时候使用Struct vs. OpenStruct?
- 数组到哈希Ruby
- 我如何让红宝石打印一个完整的回溯而不是截断一个?
- 如何使用RSpec的should_raise与任何类型的异常?
- 如何创建退出消息
- 忽略GEM,因为没有构建它的扩展