[英]What is the <= operator on Ruby Classes?
following snippet is from rails code 以下代码段来自rails代码
def rescue_from(*klasses, &block)
options = klasses.extract_options!
unless options.has_key?(:with)
if block_given?
options[:with] = block
else
raise ArgumentError, "Need a handler. Supply an options hash that has a :with key as the last argument."
end
end
klasses.each do |klass|
key = if klass.is_a?(Class) && klass <= Exception
klass.name
elsif klass.is_a?(String)
klass
else
raise ArgumentError, "#{klass} is neither an Exception nor a String"
end
# put the new handler at the end because the list is read in reverse
self.rescue_handlers += [[key, options[:with]]]
end
end
end
Notice the operator <= 注意运算符<=
what is that? 那是什么?
See http://ruby-doc.org/core/classes/Module.html#M001669 for documentation on all the comparison operators exposed by Modules (and therefore Classes). 有关Module(以及Classes)公开的所有比较运算符的文档,请参见http://ruby-doc.org/core/classes/Module.html#M001669 。
In this specific case: "Returns true if mod is a subclass of other or is the same as other. Returns nil if there's no relationship between the two. (Think of the relationship in terms of the class definition: "class A < B" implies "A < B")." 在这种特殊情况下:“如果mod是其他的子类或者与其他类似,则返回true。如果两者之间没有关系,则返回nil。(根据类定义考虑关系:”A <B <暗示“A <B”)。“
It's comparable to the is_a?
它与
is_a?
相当is_a?
method which returns true if the receiver class is a subclass of the argument; 如果接收者类是参数的子类,则返回true的方法; consider:
考虑:
Fixnum.superclass # => Integer
Fixnum <= Integer # => true
it's the operator for "LHS is an the same class as or Subclass of RHS". 它是“LHS与RHS的同类或RCS的子类”的运算符。 < is the operator for "LHS is a subclass of RHS."
<是“LHS是RHS的子类”的运营商。
This is wacky overloading of operators, but note that subclass declarations in Ruby also use < , as in 这是运算符的古怪重载,但请注意Ruby中的子类声明也使用<,如
class SomeClass < ActiveRecord::Base
so at least it's consistent in that sense. 所以至少它在这个意义上是一致的。
(LHS: left hand side, RHS: right hand side) (LHS:左手边,RHS:右手边)
Pretty sure that means klass is a type of exception. 很确定这意味着klass是一种例外。
Typically though that means 'less than or equal to'. 通常这意味着“小于或等于”。 So that code could be saying if it's at least a class but not an exception...do something.
所以代码可能会说它是否至少是一个类但不是例外......做点什么。 But then the architecture of 'less than' would be out of place.
但是,“少于”的架构将是不合适的。
From the Code Documentation 来自代码文档
# Handlers are inherited.
#handler是继承的。 They are searched from right to left, from
从右到左搜索它们
# bottom to top, and up the hierarchy.#bottom to top,以及层次结构。 The handler of the first class for
第一类的处理程序
# which exception.is_a?(klass) holds true is the one invoked, if any.#signan.is_a?(klass)成立的#是被调用的,如果有的话。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.