简体   繁体   中英

What is the <= operator on Ruby Classes?

following snippet is from rails code

  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).

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")."

It's comparable to the is_a? method which returns true if the receiver class is a subclass of the argument; consider:

Fixnum.superclass # => Integer
Fixnum <= Integer # => true

it's the operator for "LHS is an the same class as or Subclass of RHS". < is the operator for "LHS is a subclass of RHS."

This is wacky overloading of operators, but note that subclass declarations in Ruby also use < , as in

 class SomeClass < ActiveRecord::Base

so at least it's consistent in that sense.

(LHS: left hand side, RHS: right hand side)

Pretty sure that means klass is a type of exception.

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. They are searched from right to left, from
# bottom to top, and up the hierarchy. The handler of the first class for
# which exception.is_a?(klass) holds true is the one invoked, if any.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM