如何在Ruby中编写switch语句?
当前回答
由于switch-case始终返回单个对象,因此我们可以直接打印其结果:
puts case a
when 0
"It's zero"
when 1
"It's one"
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子句附加多个&&表达式。
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在2.7中引入了模式匹配
这是一个超级强大的功能
它也使用case,但有另一种语法
还有查找模式功能
users =
{ users:
[
{ user: 'user', email: 'user@user.com' },
{ user: 'admin', email: 'admin@admin.com' },
]
}
case users
in users: [*, { user:, email: /admin/ => admin_email }, *]
puts admin_email
else
puts "No admin"
end
# will print admin@admin.com
与通常情况不同,如果条件不匹配,将抛出NoMatchingPatternError。所以你可能不得不使用else分支
根据您的情况,您可能更喜欢使用方法散列。
如果有一个很长的时间列表,并且每个时间都有一个具体的值可以比较(而不是一个间隔),那么声明一个方法散列,然后从散列中调用相关的方法会更有效。
# 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 expression
when condtion1
function
when condition2
function
else
function
end
推荐文章
- 什么是Ruby文件。开放模式和选项?
- Ruby数组到字符串的转换
- 如何分割(块)一个Ruby数组成X元素的部分?
- Ruby中“or”和||的区别?
- 如何测试参数是否存在在轨道
- 开关语句:必须默认为最后一种情况?
- 在Ruby中不创建新字符串而修饰字符串的规范方法是什么?
- RVM不是一个函数,用' RVM use…’不会起作用
- 了解Gemfile。锁文件
- 如何确定一个数组是否包含另一个数组的所有元素
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- 有效,但毫无价值的语法在开关情况下?
- 最好的打印散列的方法
- Rails:dependent =>:destroy VS:dependent =>:delete_all
- 我可以在不包含Ruby模块的情况下调用实例方法吗?