简体   繁体   中英

Ruby limit types of class passed to a method?

What i stumbled upon just now - how to easily limit verity of classes that are passed to one method to only one class type ? ex. code:

class S
  attr_reader :s
  def initialize(s = nil)
    @s = s || 14
  end
end

class Gets
  def self.read(s)
    s.s
  end

end

s=S.new
p Gets.read(s) # 14

Let's say that class S has a more complex structure and i want to be sure that only that class could be passed to Gets#read method, how can i do that?

class Gets
  def self.read(s)
    raise ArgumentError unless s.kind_of?(S)
    s.s
  end
end

While to solution of sawa definitely is valid and does exactly what you want. In dynamic languages like ruby it's actually more common to use duck typing .

The idea is to just assert to which messages the attribute must respond to. This allows to easily pass in eg a different implementation.

class Gets
  def self.read(obj)
    raise ArgumentError, "must implement #s" unless obj.respond_to?(:s)
    obj.s
  end
end

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