0

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?

4

2 回答 2

4
class Gets
  def self.read(s)
    raise ArgumentError unless s.kind_of?(S)
    s.s
  end
end
于 2013-04-24T09:51:28.987 回答
4

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 e.g. a different implementation.

class Gets
  def self.read(obj)
    raise ArgumentError, "must implement #s" unless obj.respond_to?(:s)
    obj.s
  end
end
于 2013-04-24T09:56:08.907 回答