0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ActiveSupport::HashWithIndifferentAccessとは

Last updated at Posted at 2024-12-29
  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}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?