DEV Community

@kon_yu
@kon_yu

Posted on

3 2

How to check if a particular method exists in a Ruby class and instance

Prerequisites.
Ruby: 2.5.1

Checking the existence of a method for a class

Using method_defined?

String.method_defined?(:to_i)
=> true

# I see that there is a to_i method, so I'm going to run it
"1".to_i
=> 1
Enter fullscreen mode Exit fullscreen mode

Does the method exist for the instance?

Using respond_to?

"string".respond_to?(:to_a)
=> false

# There is no to_a method so I get a NoMethodError error when I try to run it
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay