我的应用程序(Ruby 1.9.2)可能会引发不同的异常,包括网络连接中断.我rescue Exception => e,然后case/when以不同的方式处理它们,但是几个错误直接通过我的案例else.
rescue Exception => e
p e.class
case e.class
when Errno::ECONNRESET
p 1
when Errno::ECONNRESET,Errno::ECONNABORTED,Errno::ETIMEDOUT
p 2
else
p 3
end
end
Run Code Online (Sandbox Code Playgroud)
打印:
Errno::ECONNRESET
3
Run Code Online (Sandbox Code Playgroud) def my_method(parameter)
if <what should be here?>
puts "parameter is a string"
elsif <and here?>
puts "parameter is a symbol"
end
end
Run Code Online (Sandbox Code Playgroud) 在Ruby中Integer === 5返回true.同样String === "karthik"回报true.
但是,5 === Integer退货false.并且"karthik" === String.
为什么操作员不能交换?
在case语句中使用类对象的最佳方法是什么?假设我有a一个Class类的实例.我想将它与不同的类相匹配.如果我做
case a
when String then ...
when Fixnum then ...
end
Run Code Online (Sandbox Code Playgroud)
这不会给出预期的结果,因为即使a == String例如a === String不是这样.这样做的聪明方法是什么?