Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

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 # => {}