Tbpgr Blog

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

Ruby | Hash | try_convert

概要

Hash.try_convert

詳細

対象オブジェクトのto_hashにより、Hashへの変換を試みます。
変換できなかった場合はnilを返却します。

サンプル

コード
# encoding: utf-8
require 'tbpgr_utils'
require 'attributes_initializable'
require "active_support/core_ext/object/instance_variables"

class Hoge
  include AttributesInitializable
  attr_accessor_init :hoge, :hige

  def to_hash
    instance_variables.reduce({}) do |hash, var|
      hash[var.to_s.delete("@").to_sym] = instance_variable_get(var)
      hash
    end
  end
end

hoge = Hoge.new hoge: "hoge", hige: "hige"


bulk_puts_eval binding, <<-EOS
Hash.try_convert hige: :hige, hoge: :hoge
Hash.try_convert "hoge=>hoge"
Hash.try_convert hoge
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils
出力
Hash.try_convert hige: :hige, hoge: :hoge # => {:hige=>:hige, :hoge=>:hoge}
Hash.try_convert "hoge=>hoge" # => nil
Hash.try_convert hoge # => {:hoge=>"hoge", :hige=>"hige"}