本文简要介绍ruby语言中 Kernel.catch 的用法。
用法
catch([tag]) {|tag| block } → obj
catch 执行其块。如果未调用throw,则块将正常执行,并且catch 返回最后计算的表达式的值。
catch(1) { 123 } # => 123
如果调用 throw(tag2, val),Ruby 会在其堆栈中搜索 catch 块,其 tag 具有与 tag2 相同的 object_id 。找到后,该块将停止执行并返回 val(如果没有给 throw 提供第二个参数,则返回 nil)。
catch(1) { throw(1, 456) } # => 456
catch(1) { throw(1) } # => nil
当tag 作为第一个参数传递时,catch 将其作为块的参数。
catch(1) {|x| x + 2 } # => 3
当没有给出 tag 时,catch 产生一个新的唯一对象(从 Object.new 开始)作为块参数。然后可以将此对象用作 throw 的参数,并将匹配正确的 catch 块。
catch do |obj_A|
catch do |obj_B|
throw(obj_B, 123)
puts "This puts is not reached"
end
puts "This puts is displayed"
456
end
# => 456
catch do |obj_A|
catch do |obj_B|
throw(obj_A, 123)
puts "This puts is still not reached"
end
puts "Now this puts is also not reached"
456
end
# => 123
相关用法
- Ruby Kernel.caller用法及代码示例
- Ruby Kernel.class用法及代码示例
- Ruby Kernel.clone用法及代码示例
- Ruby Kernel.local_variables用法及代码示例
- Ruby Kernel.Integer用法及代码示例
- Ruby Kernel.binding用法及代码示例
- Ruby Kernel.frozen?用法及代码示例
- Ruby Kernel.`cmd`用法及代码示例
- Ruby Kernel.autoload用法及代码示例
- Ruby Kernel.loop用法及代码示例
- Ruby Kernel.Hash用法及代码示例
- Ruby Kernel.set_trace_func用法及代码示例
- Ruby Kernel.exit!用法及代码示例
- Ruby Kernel.trap用法及代码示例
- Ruby Kernel.String用法及代码示例
- Ruby Kernel.select用法及代码示例
- Ruby Kernel.syscall用法及代码示例
- Ruby Kernel.then用法及代码示例
- Ruby Kernel.sprintf用法及代码示例
- Ruby Kernel.Pathname用法及代码示例
- Ruby Kernel.srand用法及代码示例
- Ruby Kernel.yield_self用法及代码示例
- Ruby Kernel.BigDecimal用法及代码示例
- Ruby Kernel.raise用法及代码示例
- Ruby Kernel.test用法及代码示例
注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Kernel.catch。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
