我记得
Ruby 2.0中的case语句允许使用procs,但我不能谷歌.
我试过检查Ruby 2.0.0 NEWS和How to write a switch statement in Ruby.我也访问了http://ruby-doc.org,但是关键字的链接是Ruby 1.9,而不是Ruby 2.0.
案件陈述中是否允许触发?
解决方法
是.
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:
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子句获取子句中的值并在其上调用===方法,将参数传递给case语句.所以,例如,这段代码……
case "cats" when /^cat/ then puts("line starts with cat!") when /^dog/ then puts("line starts with dog!") end
…运行/ ^ cat / ===“cats”来判断它是否匹配; RegExp类定义了===方法来执行正则表达式匹配.因此,只要为它定义===,就可以在when子句中使用自己的对象.
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!