LoginSignup
18
16

More than 5 years have passed since last update.

ruby2.0.0 では nil に to_h メソッドがあるらしい。

Posted at

ruby 2.0.0 から Nil#to_h が追加されました。これの何が嬉しいかというと、
ruby 1.9.3 以前だと Hashクラスを期待するオブジェクトがnilだった場合の対応として、オブジェクトに{}を代入して、nilからHashオブジェクトに変換して、後の処理を同一に出来るようにしたりします。(僕だけですかね)

hash_error.rb
# 変換しないままだと、添字メソッドを呼ぶことが出来ず例外が発生する。
def hash_error(hash)
  hash["hoge"] # デフォルトを定義しない場合
end

hash_error({"hoge" => "fuga"}) #=> "fuga"
hash_error(nil) #=> undefined method `[]' for nil:NilClass (NoMethodError)
hash_normal.rb
# 変換すると添字メソッドが呼ばれ例外が発生せず、nilが返る({}なので"hoge"キーは定義されていない
def hash_normal(hash)
  (hash || {})["hoge"] # デフォルトを定義する場合
end

hash_normal({"hoge" => "fuga"}) #=> "fuga"
hash_normal(nil) #=> nil

今までは、このように (hash || {}) としてnil回避をしていましたが、ruby2.0.0からはNil#to_hが追加されたので、以下のように書くことが出来ます。

hash_normal2.rb
def hash_normal(hash)
  hash.to_h["hoge"] # ruby2.0.0 では to_h でデフォルト定義ができる。
end

これでまた一つrubyから記号が消えたのであった。

18
16
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
18
16