LoginSignup
25
21

More than 5 years have passed since last update.

Ruby でちゃんとオブジェクトの型チェック ( 整数 ) してみた

Posted at

最初、引数の数字 (整数) チェックを下記みたいに integer? を使ってたけど、 nil とか String とか渡ってきたら、
NoMethodError なっちゃうことに気付き、ちゃんとチェックしてみた。

def hoge(sample_number)
  if sample_number.integer?
   # hogehoge
  end
end

is_a? や、instance_of? を使えば型チェックできる。

違いは、is_a? はレシーバが属するクラスの親クラスやインクルードしているモジュールを klass に指定しても true が返るけど、
instance_of? はレシーバが直接的に属するクラスを指定したときだけ true を返す

数値型のクラス構成は下記のようになっている

Numeric        # 数値クラスの親クラス
  ├ Integer    # 整数の親クラス
  │   ├ Bignum # 大きな整数
  │   └ Fixnum # 整数
  └ Float      # 浮動小数点数

上記を踏まえて、console で実行してみる

1000.class
=> Fixnum < Integer

# is_a?
1000.is_a?(Integer)
=> true
1000.is_a?(Fixnum)
=> true
1000.is_a?(Bignum)
=> false

# instance_of?
1000.instance_of?(Integer)
=> false
1000.instance_of?(Fixnum)
=> true
1000.instance_of?(Bignum)
=> false

今回は単純に整数値をチェックしたかったので、is_a?(Integer) を使うことにした。

ちなみに、is_a?kind_of? というエイリアスがあるので、もし kind_of? のメソッドを知らなくても、
メソッド名からオブジェクトの種類をチェックしているのかと予想がつくので、そっちを使う方がいいかも。

def hoge(sample_number)
  if sample_number.kind_of?(Integer)
   # hogehoge
  end
end

参考URL
is_a?,kind_of?
instance_of
Bignum、Fixnumの境界値

25
21
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
25
21