[英]What is the <= operator on Ruby Classes?
以下代碼段來自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
注意運算符<=
那是什么?
有關Module(以及Classes)公開的所有比較運算符的文檔,請參見http://ruby-doc.org/core/classes/Module.html#M001669 。
在這種特殊情況下:“如果mod是其他的子類或者與其他類似,則返回true。如果兩者之間沒有關系,則返回nil。(根據類定義考慮關系:”A <B <暗示“A <B”)。“
它與is_a?
相當is_a?
如果接收者類是參數的子類,則返回true的方法; 考慮:
Fixnum.superclass # => Integer
Fixnum <= Integer # => true
它是“LHS與RHS的同類或RCS的子類”的運算符。 <是“LHS是RHS的子類”的運營商。
這是運算符的古怪重載,但請注意Ruby中的子類聲明也使用<,如
class SomeClass < ActiveRecord::Base
所以至少它在這個意義上是一致的。
(LHS:左手邊,RHS:右手邊)
很確定這意味着klass是一種例外。
通常這意味着“小於或等於”。 所以代碼可能會說它是否至少是一個類但不是例外......做點什么。 但是,“少於”的架構將是不合適的。
來自代碼文檔
#handler是繼承的。 從右到左搜索它們
#bottom to top,以及層次結構。 第一類的處理程序
#signan.is_a?(klass)成立的#是被調用的,如果有的話。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.