コード日進月歩

しんくうの技術的な小話、メモ、つれづれ、など

Rubyにおいてnilでも使えるメソッドを眺める

他の言語だとだいたいExceptionが起きるNULLだけど、rubyの場合は結構メソッドが用意されているので割と動いてくれる。そのメソッドたちを調べた

環境

$ ruby -v
ruby 2.5.3p105 (2018-10-18 revision 65156) [x86_64-darwin18]

検証

使えるものを調べる

nil.public_methods
=> [:to_c, :&, :nil?, :===, :to_s, :inspect, :to_r, :to_i, :to_a, :to_h, :rationalize, :|, :to_f, :^, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :instance_variable_get, :public_methods, :instance_variables, :method, :public_method, :define_singleton_method, :public_send, :singleton_method, :extend, :pp, :to_enum, :enum_for, :<=>, :=~, :!~, :eql?, :respond_to?, :freeze, :object_id, :send, :display, :hash, :class, :singleton_class, :clone, :itself, :dup, :taint, :yield_self, :untaint, :tainted?, :untrusted?, :untrust, :frozen?, :trust, :methods, :singleton_methods, :protected_methods, :private_methods, :!, :equal?, :instance_eval, :==, :instance_exec, :!=, :__id__, :__send__]

結構ある。

使いがちなものダイジェスト

.to系

だいたい空とか0に準じるものになる。

nil.to_i
#=> 0
nil.to_f
#=> 0.0
nil.to_a
#=> []
nil.to_h
#=> {}
nil.to_s
#=> ""

?系

王道のnil?

nil.nil?
=> true

比較

nil.eql?(nil)
=> true

クラス判断系

nil.is_a?(NilClass)
=> true

nil.kind_of?(Integer)
=> false

参考リンク