def with_indifferent_access
ActiveSupport::HashWithIndifferentAccess.new(self)
end
ハッシュのサブクラス
ActiveSupport::HashWithIndifferentAccess < Hash
ハッシュを生成できる シンボルと文字列を同じキーとして割り当ててくれる
キー:foo
と"foo"
を同じとみなされるハッシュを実装する
Implements a hash where keys :foo and "foo" are considered to be the same.
irb(main):001:0> rgb = ActiveSupport::HashWithIndifferentAccess.new
=> {}
irb(main):002:0>
irb(main):003:0> rgb[:black] = '#000000'
=> "#000000"
irb(main):004:0> rgb[:black] # => '#000000'
=> "#000000"
irb(main):005:0> rgb['black'] # => '#000000'
=> "#000000"
irb(main):006:0>
irb(main):007:0> rgb['white'] = '#FFFFFF'
=> "#FFFFFF"
irb(main):008:0> rgb[:white] # => '#FFFFFF'
irb(main):009:0> rgb['white'] # => '#FFFFFF'
=> "#FFFFFF"
irb(main):010:0> rgb
=> {"black"=>"#000000", "white"=>"#FFFFFF"}
irb(main):007:0> rgb = ActiveSupport::HashWithIndifferentAccess.new({"black"=>"#000000", "white"=>"#FFFFFF"})
=> {"black"=>"#000000", "white"=>"#FFFFFF"}
irb(main):008:0> rgb["black"]
=> "#000000"
irb(main):009:0> rgb[:black]
=> "#000000"
書き込みインターフェース全体でキーとして使われる時内部的にはシンボルは文字列にマッピングされる。このマッピングはパブリックインターフェースに属しています。
Internally symbols are mapped to strings when used as keys in the entire writing interface (calling []=, merge, etc). This mapping belongs to the public interface. For example, given:
irb(main):011:0> hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)
=> {"a"=>1}