如何在Ruby中编写switch语句?
当前回答
案例什么时候
为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平等和对象比较”是一个很好的话题讨论。
根据您的情况,您可能更喜欢使用方法散列。
如果有一个很长的时间列表,并且每个时间都有一个具体的值可以比较(而不是一个间隔),那么声明一个方法散列,然后从散列中调用相关的方法会更有效。
# 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])
如果您需要“小于”或“大于”:
case x
when 1..5
"It's between 1 and 5"
when 6
"It's 6"
when 7..1.0/0
"It's equal or greater than 7"
when -1.0/0..0
"It's equal or less than 0"
end
1.0/0等于Float::INFINITY,因此您可以使用自己喜欢的。
在Ruby 2.6之后,您可以使用Endless Ranges,在Ruby 2.7之后,您还可以使用Beginless Ranges,例如:
case x
when 1..5
"It's between 1 and 5"
when 6
"It's 6"
when (7..)
"It's equal or greater than 7"
when (..0)
"It's equal or less than 0"
end
你可以用更自然的方式这样做,
case expression
when condtion1
function
when condition2
function
else
function
end
在when子句中强调逗号(,)至关重要。它充当if语句的||,也就是说,它在when子句的分隔表达式之间进行OR比较,而不是and比较。参见以下案例陈述:
x = 3
case x
when 3, x < 2 then 'apple'
when 3, x > 2 then 'orange'
end
=> "apple"
x不小于2,但返回值为“apple”。为什么?因为x是3,并且由于“,”充当||,所以它不必计算表达式x<2。
您可能认为,要执行AND,可以执行以下操作,但它不起作用:
case x
when (3 && x < 2) then 'apple'
when (3 && x > 2) then 'orange'
end
=> nil
它不起作用,因为(3&&x>2)的计算结果为true,Ruby获取true值,并将其与x进行比较,使用==,这是不正确的,因为x是3。
要进行&&比较,您必须将case视为if/else块:
case
when x == 3 && x < 2 then 'apple'
when x == 3 && x > 2 then 'orange'
end
在《Ruby编程语言》一书中,Matz表示后一种形式是简单的(而且很少使用)形式,它只是if/elsif/else的一种替代语法。然而,无论它是否不经常使用,我看不到任何其他方法可以为给定的when子句附加多个&&表达式。