4
1

More than 1 year has passed since last update.

【Ruby】変数が定義されているかを確認

Last updated at Posted at 2022-11-10

defined?を使用する

Rubyでは変数が定義されているかを確認するためにdefined?を使用できます。
defined?は変数やメソッドが定義済みの場合、式の種類を表す文字列を戻り値として返します。
未定義の場合、nilを戻り値として返します。

  • 変数に値が代入されていると"local-variable"が返ってきます。
> test = 111
=> 111
> defined? test
=> "local-variable"
  • nilが代入されていても"local-variable"が返ってきます。
> hoge = nil
=> nil
> defined? hoge
=> "local-variable"
  • 変数に値が代入されていないとnilが返ってきます。
> defined? foo
=> nil
  • グローバル変数に値が代入されていると"global-variable"が返ってきます。
> $global = 111
=> 111
> defined? $global
=> "global-variable"
  • 以下の場合は"assignment"が返ってきます。変数に値は代入されていません。
> defined? bar = 111
=> "assignment"
> p bar
nil
=> nil
  • メソッドの場合は"method"が返ってきます。
> defined? puts
=> "method"
  • defined?の場合はエラーが返ってきます。
> defined? defined?
Traceback (most recent call last):
        3: from /usr/bin/irb:23:in `<main>'
        2: from /usr/bin/irb:23:in `load'
        1: from /Library/Ruby/Gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>'
SyntaxError ((irb):7: syntax error, unexpected end-of-input)

参考

4
1
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
4
1