v-crn Code Log

主に備忘録

Rubyで変数が定義されているか確認する

defined?

Rubyで変数が定義されているか確認するにはdefined?メソッドを使用する。defined?は引数として入れた変数やメソッドが定義済みであれば式の種別を表す文字列を返す。未定義であればnilを返す。

>> a = 1
>> defined? a
=> "local-variable"

>> hoge = nil
>> defined? hoge
=> "local-variable"

>> defined? poke
=> nil

>> defined? puts
=> "method"

>> defined? defined?
Traceback (most recent call last):
SyntaxError ((irb):10: syntax error, unexpected end-of-input)
defined? defined?
                 ^

参考

クラス/メソッドの定義 (Ruby 2.6.0)

ruby on rails - How to check if a variable exists with a value without "undefined local variable or method"? - Stack Overflow