LoginSignup
0
2

More than 5 years have passed since last update.

Rubyのクラスとインスタンスで特定のメソッドが存在するかどうか調べる方法

Posted at

前提条件
Ruby: 2.5.1

クラスに対してメソッドの存在を確認する

method_defined?を使う

String.method_defined?(:to_i)
=> true

# to_iメソッドあることがわかるので実行してみる
"1".to_i
=> 1

インスタンスに対してメソッドが存在するか

respond_to?を使う

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

# to_aメソッドがないので実行してみるとNoMethodErrorエラーになる
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2