以下の内容はhttps://tbpgr.hatenablog.com/entry/20140411/1397227262より取得しました。


Ruby | Ruby2.0新規要素 | Nil#to_hの追加

概要

Nil#to_hの追加

詳細

Nil#to_hの追加されたことによって
to_hメソッドによってハッシュへの変換を期待するクラスがある場合に、
対象がnilでもエラーにならなくなった。

サンプルコード
# encoding: utf-8
require 'tbpgr_utils'
require 'attributes_initializable'
require 'attributes_hashable'

class Person
  include AttributesInitializable
  attr_accessor_init :name, :age
  include AttributesHashable

  alias_method :to_h, :to_hash
end

hoge = Person.new({name: 'hoge', age: 49})
hige = nil

[hoge, hige].each do |h|
  bulk_puts_eval binding, <<-EOS
h.to_h
  EOS
end
***出力
>||
h.to_h # => {:name=>"hoge", :age=>49}
h.to_h # => {}



以上の内容はhttps://tbpgr.hatenablog.com/entry/20140411/1397227262より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14