respond_to?(method_name) — kiểm tra object có thể respond với method đó không (duck typing). Trả false với private method mặc định, trừ khi truyền true làm arg thứ 2.
is_a?(klass) / kind_of?(klass) — kiểm tra object thuộc class/module đó không (type checking). Cả hai là alias nhau.
str = "hello"
str.respond_to?(:upcase) # => true
str.respond_to?(:nonexist) # => false
str.is_a?(String) # => true
str.is_a?(Comparable) # => true — cả module
# Ưu tiên respond_to? cho duck typing:
def process(obj)
if obj.respond_to?(:read)
obj.read
else
raise ArgumentError, "Expected a readable object"
end
endDùng respond_to? khi viết generic code (không quan tâm class, chỉ quan tâm hành vi — đúng tinh thần Ruby).
Dùng is_a? khi cần xác nhận type thật sự (bất thường trong Ruby thuần, phổ biến hơn khi tương tác với C extension/API bên ngoài).
respond_to?(method_name) — checks whether an object can respond to a method (duck typing). Returns false for private methods by default; pass true as a second arg to include them.
is_a?(klass) / kind_of?(klass) — checks whether an object belongs to a class/module. Both are aliases.
str = "hello"
str.respond_to?(:upcase) # => true
str.respond_to?(:nonexist) # => false
str.is_a?(String) # => true
str.is_a?(Comparable) # => true — modules too
def process(obj)
raise ArgumentError unless obj.respond_to?(:read)
obj.read
endPrefer respond_to? for generic/duck-typed code.
Use is_a? when type identity truly matters (e.g. interacting with C extensions or external APIs).