Tbpgr Blog

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

Ruby | Hash | store

概要

Hash#store

詳細

Hashに要素を追加する。
[]= のエイリアス

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

h = {
  hoge_key1: '1',
  hoge_key2: '2',
  hige_key: '3',
  hage_key: '4',
}

bulk_puts_eval binding, <<-EOS
h.store :hege_key, "5"
h
h.store :hage_key, "4.5"
h
EOS
__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval
attr_accessor_init

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils
出力
h.store :hege_key, "5" # => "5"
h # => {:hoge_key1=>"1", :hoge_key2=>"2", :hige_key=>"3", :hage_key=>"4", :hege_key=>"5"}
h.store :hage_key, "4.5" # => "4.5"
h # => {:hoge_key1=>"1", :hoge_key2=>"2", :hige_key=>"3", :hage_key=>"4.5", :hege_key=>"5"}