0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rubyのクラス内でインスタンス変数が定義済みかを確認する方法

Last updated at Posted at 2020-09-02
dog.rb
class Dog
  def initialize(name)
    @name = name
  end

  def set_nickname(nickname)   # rubyでset_hogeは使わないけど今回は簡略化のために大目に見て!
    @nickname = nickname
  end

  def print_nickname
    if !defined?(@nickname)
      puts('Not Set')
      return
    end
    puts(@nickname)
  end
end

if @ageを参照した時に、それがnilだった場合、以下のどちらのケースか分からない。

  • 一度も定義されていないからnilなのか
  • 一度@nickname=nilを代入した結果のnilなのか

そんな時にはdefind?(@age)を使用すべし。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?