Tbpgr Blog

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

Ruby | Hash | replace

概要

Hash#replace

詳細

Hashの内容を引数の内容に置き換える。
引数がHash以外の場合はto_hashメソッドが実装されていればHashへの変換を試みる。

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

h = {
  hoge_key1: :hoge_value,
  hoge_key2: :hoge_value,
  hige_key: :hige_value,
  hage_key: :hage_value,
}

rh = {
  replace_key: :replace_value,
}

class Hoge
  include AttributesInitializable
  attr_accessor_init :name, :age
  def to_hash
    {
      name: @name,
      age: @age,
    }
  end
end

ary = %w{hoge hige hage}
hoge = Hoge.new do |h|
  h.name = 'dhh'
  h.age = 25
end

bulk_puts_eval binding, <<-EOS
h.replace rh
h.replace hoge
EOS
__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval
attr_accessor_init

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils
出力
h.replace rh # => {:replace_key=>:replace_value}
h.replace hoge # => {:name=>"dhh", :age=>25}