跳至內容 跳至搜尋

大小寫不敏感的雜湊

實作一個將鍵 :foo"foo" 視為相同的雜湊。

rgb = ActiveSupport::HashWithIndifferentAccess.new

rgb[:black] = '#000000'
rgb[:black]  # => '#000000'
rgb['black'] # => '#000000'

rgb['white'] = '#FFFFFF'
rgb[:white]  # => '#FFFFFF'
rgb['white'] # => '#FFFFFF'

在整個寫入介面(呼叫 []=merge 等)中,當符號作為鍵使用時,它們會在內部映射到字串。此映射屬於公共介面。例如,給定

hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)

保證返回的鍵是一個字串

hash.keys # => ["a"]

技術上接受其他類型的鍵

hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)
hash[0] = 0
hash # => {"a"=>1, 0=>0}

但這個類別適用於預期鍵是字串或符號,並且將兩者理解為相同的情況。例如 Ruby on Rails 中的 params 雜湊。

請注意,核心擴展定義了 Hash#with_indifferent_access

rgb = { black: '#000000', white: '#FFFFFF' }.with_indifferent_access

這可能很方便。

要在 Rails 之外訪問此類別,請使用以下程式碼引入核心擴展

require "active_support/core_ext/hash/indifferent_access"

這將會引入此檔案。

方法
#
A
C
D
E
F
H
I
K
M
N
R
S
T
U
V
W

類別公開方法

[](*args)

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 85
def self.[](*args)
  new.merge!(Hash[*args])
end

new(constructor = nil)

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 70
def initialize(constructor = nil)
  if constructor.respond_to?(:to_hash)
    super()
    update(constructor)

    hash = constructor.is_a?(Hash) ? constructor : constructor.to_hash
    self.default = hash.default if hash.default
    self.default_proc = hash.default_proc if hash.default_proc
  elsif constructor.nil?
    super()
  else
    super(constructor)
  end
end

實體公開方法

[](key)

Hash#[] 相同,其中作為參數傳遞的鍵可以是字串或符號

counters = ActiveSupport::HashWithIndifferentAccess.new
counters[:foo] = 1

counters['foo'] # => 1
counters[:foo]  # => 1
counters[:zoo]  # => nil
# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 168
def [](key)
  super(convert_key(key))
end

[]=(key, value)

將新值賦予雜湊

hash = ActiveSupport::HashWithIndifferentAccess.new
hash[:key] = 'value'

之後可以使用 :key'key' 來擷取此值。

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 98
def []=(key, value)
  regular_writer(convert_key(key), convert_value(value, conversion: :assignment))
end

assoc(key)

Hash#assoc 相同,其中作為參數傳遞的鍵可以是字串或符號

counters = ActiveSupport::HashWithIndifferentAccess.new
counters[:foo] = 1

counters.assoc('foo') # => ["foo", 1]
counters.assoc(:foo)  # => ["foo", 1]
counters.assoc(:zoo)  # => nil
# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 181
def assoc(key)
  super(convert_key(key))
end

compact()

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 371
def compact
  dup.tap(&:compact!)
end

deep_symbolize_keys()

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 320
def deep_symbolize_keys; to_hash.deep_symbolize_keys! end

default(key = (no_key = true))

Hash#default 相同,其中作為參數傳遞的鍵可以是字串或符號

hash = ActiveSupport::HashWithIndifferentAccess.new(1)
hash.default                   # => 1

hash = ActiveSupport::HashWithIndifferentAccess.new { |hash, key| key }
hash.default                   # => nil
hash.default('foo')            # => 'foo'
hash.default(:foo)             # => 'foo'
# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 223
def default(key = (no_key = true))
  if no_key
    super()
  else
    super(convert_key(key))
  end
end

delete(key)

從雜湊中移除指定的鍵。

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 303
def delete(key)
  super(convert_key(key))
end

dig(*args)

與 `Hash#dig` 相同,其中作為參數傳遞的鍵可以是字串或符號

counters = ActiveSupport::HashWithIndifferentAccess.new
counters[:foo] = { bar: 1 }

counters.dig('foo', 'bar')     # => 1
counters.dig(:foo, :bar)       # => 1
counters.dig(:zoo)             # => nil
# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 208
def dig(*args)
  args[0] = convert_key(args[0]) if args.size > 0
  super(*args)
end

dup()

傳回雜湊的淺拷貝(shallow copy)。

hash = ActiveSupport::HashWithIndifferentAccess.new({ a: { b: 'b' } })
dup  = hash.dup
dup[:a][:c] = 'c'

hash[:a][:c] # => "c"
dup[:a][:c]  # => "c"
# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 264
def dup
  self.class.new(self).tap do |new_hash|
    set_defaults(new_hash)
  end
end

except(*keys)

傳回一個具有不區分大小寫的雜湊,其中包含除給定鍵之外的所有內容。

hash = { a: "x", b: "y", c: 10 }.with_indifferent_access
hash.except(:a, "b") # => {c: 10}.with_indifferent_access
hash                 # => { a: "x", b: "y", c: 10 }.with_indifferent_access
別名:without
# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 311
def except(*keys)
  dup.except!(*keys)
end

extractable_options?()

傳回 `true`,以便 `Array#extract_options!` 找到此類別的成員。

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 58
def extractable_options?
  true
end

fetch(key, *extras)

與 `Hash#fetch` 相同,其中作為參數傳遞的鍵可以是字串或符號

counters = ActiveSupport::HashWithIndifferentAccess.new
counters[:foo] = 1

counters.fetch('foo')          # => 1
counters.fetch(:bar, 0)        # => 0
counters.fetch(:bar) { |key| 0 } # => 0
counters.fetch(:zoo)           # => KeyError: key not found: "zoo"
# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 195
def fetch(key, *extras)
  super(convert_key(key), *extras)
end

fetch_values(*indices, &block)

傳回指定索引處的值的陣列,但當找不到其中一個鍵時,也會引發異常。

hash = ActiveSupport::HashWithIndifferentAccess.new
hash[:a] = 'x'
hash[:b] = 'y'
hash.fetch_values('a', 'b') # => ["x", "y"]
hash.fetch_values('a', 'c') { |key| 'z' } # => ["x", "z"]
hash.fetch_values('a', 'c') # => KeyError: key not found: "c"
# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 251
def fetch_values(*indices, &block)
  indices.map! { |key| convert_key(key) }
  super
end

has_key?(key)

別名:key?

include?(key)

別名:key?

key?(key)

檢查雜湊中是否有與傳入的參數匹配的鍵

hash = ActiveSupport::HashWithIndifferentAccess.new
hash['key'] = 'value'
hash.key?(:key)  # => true
hash.key?('key') # => true
# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 151
def key?(key)
  super(convert_key(key))
end

member?(key)

別名:key?

merge(*hashes, &block)

此方法與 `update` 的語義相同,但它不會修改接收者,而是傳回一個新的具有不區分大小寫的雜湊,其中包含合併的結果。

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 273
def merge(*hashes, &block)
  dup.update(*hashes, &block)
end

merge!(*other_hashes, &block)

別名:update

nested_under_indifferent_access()

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 66
def nested_under_indifferent_access
  self
end

regular_update(*other_hashes, &block)

別名:update

regular_writer(key, value)

別名:[]=

reject(*args, &block)

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 328
def reject(*args, &block)
  return to_enum(:reject) unless block_given?
  dup.tap { |hash| hash.reject!(*args, &block) }
end

replace(other_hash)

使用 other_hash 替換此雜湊的內容。

h = { "a" => 100, "b" => 200 }
h.replace({ "c" => 300, "d" => 400 }) # => {"c"=>300, "d"=>400}
# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 298
def replace(other_hash)
  super(self.class.new(other_hash))
end

reverse_merge(other_hash)

類似於 `merge`,但順序相反:將接收者合併到參數中,並傳回一個新的具有不區分大小寫的雜湊作為結果

hash = ActiveSupport::HashWithIndifferentAccess.new
hash['a'] = nil
hash.reverse_merge(a: 0, b: 1) # => {"a"=>nil, "b"=>1}
別名:with_defaults
# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 283
def reverse_merge(other_hash)
  super(self.class.new(other_hash))
end

reverse_merge!(other_hash)

reverse_merge 語義相同,但會直接修改接收者。

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 289
def reverse_merge!(other_hash)
  super(self.class.new(other_hash))
end

select(*args, &block)

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 323
def select(*args, &block)
  return to_enum(:select) unless block_given?
  dup.tap { |hash| hash.select!(*args, &block) }
end

slice(*keys)

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 361
def slice(*keys)
  keys.map! { |key| convert_key(key) }
  self.class.new(super)
end

slice!(*keys)

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 366
def slice!(*keys)
  keys.map! { |key| convert_key(key) }
  super
end

store(key, value)

別名:[]=

symbolize_keys()

別名:to_options
# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 318
def symbolize_keys; to_hash.symbolize_keys! end

to_hash()

轉換為使用字串鍵的正規雜湊。

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 376
def to_hash
  copy = Hash[self]
  copy.transform_values! { |v| convert_value_to_hash(v) }
  set_defaults(copy)
  copy
end

to_options()

to_options!()

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 321
def to_options!; self end

to_proc()

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 383
def to_proc
  proc { |key| self[key] }
end

transform_keys(hash = NOT_GIVEN, &block)

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 340
def transform_keys(hash = NOT_GIVEN, &block)
  return to_enum(:transform_keys) if NOT_GIVEN.equal?(hash) && !block_given?
  dup.tap { |h| h.transform_keys!(hash, &block) }
end

transform_keys!(hash = NOT_GIVEN, &block)

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 345
def transform_keys!(hash = NOT_GIVEN, &block)
  return to_enum(:transform_keys!) if NOT_GIVEN.equal?(hash) && !block_given?

  if hash.nil?
    super
  elsif NOT_GIVEN.equal?(hash)
    keys.each { |key| self[yield(key)] = delete(key) }
  elsif block_given?
    keys.each { |key| self[hash[key] || yield(key)] = delete(key) }
  else
    keys.each { |key| self[hash[key] || key] = delete(key) }
  end

  self
end

transform_values(&block)

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 333
def transform_values(&block)
  return to_enum(:transform_values) unless block_given?
  dup.tap { |hash| hash.transform_values!(&block) }
end

update(*other_hashes, &block)

直接更新接收者,合併作為參數傳入的雜湊。

hash_1 = ActiveSupport::HashWithIndifferentAccess.new
hash_1[:key] = 'value'

hash_2 = ActiveSupport::HashWithIndifferentAccess.new
hash_2[:key] = 'New Value!'

hash_1.update(hash_2) # => {"key"=>"New Value!"}

hash = ActiveSupport::HashWithIndifferentAccess.new
hash.update({ "a" => 1 }, { "b" => 2 }) # => { "a" => 1, "b" => 2 }

參數可以是 ActiveSupport::HashWithIndifferentAccess 或正規的 Hash。 無論哪種情況,合併都會遵循 indifferent access 的語義。

如果參數是具有鍵 :key"key" 的正規雜湊,則只有一個值會保留在接收者中,但未指定是哪一個。

當給定一個區塊時,重複鍵的值將由調用區塊的結果決定,該區塊包含重複的鍵、接收者中的值和 other_hash 中的值。 重複鍵的規則遵循 indifferent access 的語義。

hash_1[:key] = 10
hash_2['key'] = 12
hash_1.update(hash_2) { |key, old, new| old + new } # => {"key"=>22}
# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 132
def update(*other_hashes, &block)
  if other_hashes.size == 1
    update_with_single_argument(other_hashes.first, block)
  else
    other_hashes.each do |other_hash|
      update_with_single_argument(other_hash, block)
    end
  end
  self
end

values_at(*keys)

返回指定索引處的值的陣列。

hash = ActiveSupport::HashWithIndifferentAccess.new
hash[:a] = 'x'
hash[:b] = 'y'
hash.values_at('a', 'b') # => ["x", "y"]
# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 237
def values_at(*keys)
  keys.map! { |key| convert_key(key) }
  super
end

with_defaults(other_hash)

別名:reverse_merge

with_defaults!(other_hash)

with_indifferent_access()

# File activesupport/lib/active_support/hash_with_indifferent_access.rb, line 62
def with_indifferent_access
  dup
end

without(*keys)

別名:except