procs 可以与 Ruby 2.0 中的 case 语句一起使用吗? [英] Can procs be used with case statements in Ruby 2.0?
问题描述
我记得在 Ruby 2.0 中的 case
语句中允许使用 procs,但我无法搜索它.
I remember something about procs being allowed in case
statements in Ruby 2.0, but I can't google it.
我尝试查看 Ruby 2.0.0 NEWS 和 如何在 Ruby 中编写 switch 语句.我还访问了 http://ruby-doc.org ,但它的关键字链接是 Ruby 1.9,不是 Ruby 2.0.
I tried checking Ruby 2.0.0 NEWS and How to write a switch statement in Ruby. I also visited http://ruby-doc.org , but the link it had for keywords was for Ruby 1.9, not Ruby 2.0.
在 case 语句中是否允许使用 proc?
Are procs allowed in case statements?
推荐答案
是.
2.0.0p0 :001> lamb = ->(x){ x%2==1 }
#=> #<Proc:0x007fdd6a97dd90@(irb):1 (lambda)>
2.0.0p0 :002> case 3; when lamb then p(:yay); end
:yay
#=> :yay
2.0.0p0 :003> lamb === 3
#=> true
2.0.0p0 :007> lamb === 2
#=> false
然而,这与 1.9.1 没有什么不同,因为 Proc#===
是当时定义的.由于 ruby-docs 似乎在显示此方法时有问题,要清楚文档说 proc === obj
:
However, this is no different than 1.9.1 since Proc#===
was defined back then. Since ruby-docs seems to have a problem showing this method, to be clear the documentation says that proc === obj
:
使用 obj
作为 proc 的参数调用块,如 #call
.允许一个proc对象成为case
语句中when
子句的目标.
Invokes the block with
obj
as the proc's parameter like#call
. It is to allow a proc object to be a target ofwhen
clause in acase
statement.
<小时>
对于 Ruby 初学者,那么 Ruby 的 case
语句中的 when
子句获取子句中的值并调用 ===
方法 on它,将参数传递给 case 语句.所以,例如,这段代码......
For the Ruby beginner, then when
clause in Ruby's case
statements takes the value in the clause and calls the ===
method on it, passing in the argument to the case statement. So, for example, this code…
case "cats"
when /^cat/ then puts("line starts with cat!")
when /^dog/ then puts("line starts with dog!")
end
...运行 /^cat/=== "cats"
来判断是否匹配;RegExp
类定义了 ===
方法来执行正则表达式匹配.因此,你可以在 when
子句中使用你自己的对象,只要你为它定义了 ===
.
…runs /^cat/ === "cats"
to decide if it's a match; the RegExp
class defines the ===
method to perform regex matching. Thus, you can use your own object in a when
clause as long as you define ===
for it.
Moddable = Struct.new(:n) do
def ===(numeric)
numeric % n == 0
end
end
mod4 = Moddable.new(4)
mod3 = Moddable.new(3)
12.times do |i|
case i
when mod4
puts "#{i} is a multiple of 4!"
when mod3
puts "#{i} is a multiple of 3!"
end
end
#=> 0 is a multiple of 4!
#=> 3 is a multiple of 3!
#=> 4 is a multiple of 4!
#=> 6 is a multiple of 3!
#=> 8 is a multiple of 4!
#=> 9 is a multiple of 3!
这篇关于procs 可以与 Ruby 2.0 中的 case 语句一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!