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