跳至內容 跳至搜尋
方法(Methods)
A
C
D
E
F
N
R
S
T
W

類別公開方法(Class Public methods)

from_trusted_xml(xml)

如同 `Hash.from_xml`,從 XML 建立一個 雜湊(Hash),但也允許 符號(Symbol) 和 YAML。

# File activesupport/lib/active_support/core_ext/hash/conversions.rb, line 133
def from_trusted_xml(xml)
  from_xml xml, []
end

from_xml(xml, disallowed_types = nil)

返回一個 雜湊(Hash),其中包含一組鍵值對,鍵是節點名稱,值是其內容。

xml = <<-XML
  <?xml version="1.0" encoding="UTF-8"?>
    <hash>
      <foo type="integer">1</foo>
      <bar type="integer">2</bar>
    </hash>
XML

hash = Hash.from_xml(xml)
# => {"hash"=>{"foo"=>1, "bar"=>2}}

如果 XML 包含屬性 `type="yaml"` 或 `type="symbol"`,則會引發 `DisallowedType` 錯誤。使用 `Hash.from_trusted_xml` 來解析此 XML。

也可以以陣列的形式傳入自定義的 `disallowed_types`。

xml = <<-XML
  <?xml version="1.0" encoding="UTF-8"?>
    <hash>
      <foo type="integer">1</foo>
      <bar type="string">"David"</bar>
    </hash>
XML

hash = Hash.from_xml(xml, ['integer'])
# => ActiveSupport::XMLConverter::DisallowedType: Disallowed type attribute: "integer"

請注意,傳入自定義 disallowed 類型將會覆蓋預設類型,即 符號(Symbol) 和 YAML。

# File activesupport/lib/active_support/core_ext/hash/conversions.rb, line 128
def from_xml(xml, disallowed_types = nil)
  ActiveSupport::XMLConverter.new(xml, disallowed_types).to_h
end

實例公開方法(Instance Public methods)

assert_valid_keys(*valid_keys)

驗證雜湊中的所有鍵是否與 `*valid_keys` 匹配,如果不匹配,則引發 `ArgumentError` 錯誤。

請注意,鍵的處理方式與 `HashWithIndifferentAccess` 不同,這表示字串和符號鍵將不匹配。

{ name: 'Rob', years: '28' }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: :years. Valid keys are: :name, :age"
{ name: 'Rob', age: '28' }.assert_valid_keys('name', 'age') # => raises "ArgumentError: Unknown key: :name. Valid keys are: 'name', 'age'"
{ name: 'Rob', age: '28' }.assert_valid_keys(:name, :age)   # => passes, raises nothing
# File activesupport/lib/active_support/core_ext/hash/keys.rb, line 48
def assert_valid_keys(*valid_keys)
  valid_keys.flatten!
  each_key do |k|
    unless valid_keys.include?(k)
      raise ArgumentError.new("Unknown key: #{k.inspect}. Valid keys are: #{valid_keys.map(&:inspect).join(', ')}")
    end
  end
end

compact_blank!()

從 `Hash` 中移除所有空白值並返回自身。使用 `Object#blank?` 來判斷值是否為空白。

h = { a: "", b: 1, c: nil, d: [], e: false, f: true }
h.compact_blank!
# => { b: 1, f: true }
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 232
def compact_blank!
  # use delete_if rather than reject! because it always returns self even if nothing changed
  delete_if { |_k, v| v.blank? }
end

deep_dup()

返回雜湊的深層拷貝。

hash = { a: { b: 'b' } }
dup  = hash.deep_dup
dup[:a][:c] = 'c'

hash[:a][:c] # => nil
dup[:a][:c]  # => "c"
# File activesupport/lib/active_support/core_ext/object/deep_dup.rb, line 43
def deep_dup
  hash = dup
  each_pair do |key, value|
    if ::String === key || ::Symbol === key
      hash[key] = value.deep_dup
    else
      hash.delete(key)
      hash[key.deep_dup] = value.deep_dup
    end
  end
  hash
end

deep_merge(other_hash, &block)

返回一個將 `self` 和 `other_hash` 遞迴合併的新雜湊。

h1 = { a: true, b: { c: [1, 2, 3] } }
h2 = { a: false, b: { x: [3, 4, 5] } }

h1.deep_merge(h2) # => { a: false, b: { c: [1, 2, 3], x: [3, 4, 5] } }

與標準函式庫中的 Hash#merge 一樣,可以提供一個區塊來合併值。

h1 = { a: 100, b: 200, c: { c1: 100 } }
h2 = { b: 250, c: { c1: 200 } }
h1.deep_merge(h2) { |key, this_val, other_val| this_val + other_val }
# => { a: 100, b: 450, c: { c1: 300 } }
# File activesupport/lib/active_support/core_ext/hash/deep_merge.rb, line 9
  

deep_stringify_keys()

返回一個所有鍵都轉換為字串的新雜湊。這包括根雜湊以及所有巢狀雜湊和陣列中的鍵。

hash = { person: { name: 'Rob', age: '28' } }

hash.deep_stringify_keys
# => {"person"=>{"name"=>"Rob", "age"=>"28"}}
# File activesupport/lib/active_support/core_ext/hash/keys.rb, line 84
def deep_stringify_keys
  deep_transform_keys { |k| Symbol === k ? k.name : k.to_s }
end

deep_stringify_keys!()

將所有鍵破壞性地轉換為字串。這包括根雜湊以及所有巢狀雜湊和陣列中的鍵。

# File activesupport/lib/active_support/core_ext/hash/keys.rb, line 91
def deep_stringify_keys!
  deep_transform_keys! { |k| Symbol === k ? k.name : k.to_s }
end

deep_symbolize_keys()

返回一個所有鍵都轉換為符號的新雜湊,只要它們回應 `to_sym`。這包括根雜湊以及所有巢狀雜湊和陣列中的鍵。

hash = { 'person' => { 'name' => 'Rob', 'age' => '28' } }

hash.deep_symbolize_keys
# => {:person=>{:name=>"Rob", :age=>"28"}}
# File activesupport/lib/active_support/core_ext/hash/keys.rb, line 103
def deep_symbolize_keys
  deep_transform_keys { |key| key.to_sym rescue key }
end

deep_symbolize_keys!()

將所有鍵破壞性地轉換為符號,只要它們回應 `to_sym`。這包括根雜湊以及所有巢狀雜湊和陣列中的鍵。

# File activesupport/lib/active_support/core_ext/hash/keys.rb, line 110
def deep_symbolize_keys!
  deep_transform_keys! { |key| key.to_sym rescue key }
end

**deep_transform_keys**(&block)

返回一個所有鍵都經區塊操作轉換的新雜湊。這包括根雜湊和所有巢狀雜湊和陣列中的鍵。

hash = { person: { name: 'Rob', age: '28' } }

hash.deep_transform_keys{ |key| key.to_s.upcase }
# => {"PERSON"=>{"NAME"=>"Rob", "AGE"=>"28"}}
# File activesupport/lib/active_support/core_ext/hash/keys.rb, line 65
def deep_transform_keys(&block)
  _deep_transform_keys_in_object(self, &block)
end

deep_transform_keys!(&block)

使用區塊操作破壞性地轉換所有鍵。這包括根雜湊和所有巢狀雜湊和陣列中的鍵。

# File activesupport/lib/active_support/core_ext/hash/keys.rb, line 72
def deep_transform_keys!(&block)
  _deep_transform_keys_in_object!(self, &block)
end

deep_transform_values(&block)

返回一個所有值都經區塊操作轉換的新雜湊。這包括根雜湊和所有巢狀雜湊和陣列中的值。

hash = { person: { name: 'Rob', age: '28' } }

hash.deep_transform_values{ |value| value.to_s.upcase }
# => {person: {name: "ROB", age: "28"}}
# File activesupport/lib/active_support/core_ext/hash/deep_transform_values.rb, line 12
def deep_transform_values(&block)
  _deep_transform_values_in_object(self, &block)
end

deep_transform_values!(&block)

使用區塊操作破壞性地轉換所有值。這包括根雜湊和所有巢狀雜湊和陣列中的值。

# File activesupport/lib/active_support/core_ext/hash/deep_transform_values.rb, line 19
def deep_transform_values!(&block)
  _deep_transform_values_in_object!(self, &block)
end

except!(*keys)

從雜湊中移除給定的鍵並返回它。

hash = { a: true, b: false, c: nil }
hash.except!(:c) # => { a: true, b: false }
hash             # => { a: true, b: false }
# File activesupport/lib/active_support/core_ext/hash/except.rb, line 8
def except!(*keys)
  keys.each { |key| delete(key) }
  self
end

extract!(*keys)

移除並返回與給定鍵匹配的鍵值對。

hash = { a: 1, b: 2, c: 3, d: 4 }
hash.extract!(:a, :b) # => {:a=>1, :b=>2}
hash                  # => {:c=>3, :d=>4}
# File activesupport/lib/active_support/core_ext/hash/slice.rb, line 24
def extract!(*keys)
  keys.each_with_object(self.class.new) { |key, result| result[key] = delete(key) if has_key?(key) }
end

extractable_options?()

預設情況下,只有 `雜湊(Hash)` 本身的實例是可提取的。`雜湊(Hash)` 的子類別可以實作此方法並返回 true 以宣告自身為可提取的。如果一個 `雜湊(Hash)` 是可提取的,`Array#extract_options!` 會在它是 `陣列(Array)` 的最後一個元素時將其從 `陣列(Array)` 中彈出。

# File activesupport/lib/active_support/core_ext/array/extract_options.rb, line 9
def extractable_options?
  instance_of?(Hash)
end

nested_under_indifferent_access()

在物件巢狀於接收 `with_indifferent_access` 的物件下時呼叫。此方法將由封閉物件在目前物件上呼叫,並預設設定為 `with_indifferent_access` 的別名。`雜湊(Hash)` 的子類別可以覆寫此方法以返回 `self`,如果轉換為 `ActiveSupport::HashWithIndifferentAccess` 並非理想的情況。

b = { b: 1 }
{ a: b }.with_indifferent_access['a'] # calls b.nested_under_indifferent_access
# => {"b"=>1}

reverse_merge(other_hash)

將呼叫者合併到 other_hash 中。例如:

options = options.reverse_merge(size: 25, velocity: 10)

等同於

options = { size: 25, velocity: 10 }.merge(options)

這對於使用預設值初始化選項雜湊特別有用。

別名:with_defaults
# File activesupport/lib/active_support/core_ext/hash/reverse_merge.rb, line 14
def reverse_merge(other_hash)
  other_hash.merge(self)
end

reverse_merge!(other_hash)

破壞性 reverse_merge

# File activesupport/lib/active_support/core_ext/hash/reverse_merge.rb, line 20
def reverse_merge!(other_hash)
  replace(reverse_merge(other_hash))
end

reverse_update(other_hash)

slice!(*keys)

僅保留給定鍵值,並將雜湊替換為新的雜湊。返回包含已移除鍵值對的雜湊。

hash = { a: 1, b: 2, c: 3, d: 4 }
hash.slice!(:a, :b)  # => {:c=>3, :d=>4}
hash                 # => {:a=>1, :b=>2}
# File activesupport/lib/active_support/core_ext/hash/slice.rb, line 10
def slice!(*keys)
  omit = slice(*self.keys - keys)
  hash = slice(*keys)
  hash.default      = default
  hash.default_proc = default_proc if default_proc
  replace(hash)
  omit
end

stringify_keys()

返回一個所有鍵都被轉換為字串的新雜湊。

hash = { name: 'Rob', age: '28' }

hash.stringify_keys
# => {"name"=>"Rob", "age"=>"28"}
# File activesupport/lib/active_support/core_ext/hash/keys.rb, line 10
def stringify_keys
  transform_keys { |k| Symbol === k ? k.name : k.to_s }
end

stringify_keys!()

破壞性地將所有鍵轉換為字串。與 stringify_keys 相同,但會修改 self

# File activesupport/lib/active_support/core_ext/hash/keys.rb, line 16
def stringify_keys!
  transform_keys! { |k| Symbol === k ? k.name : k.to_s }
end

symbolize_keys()

返回一個所有鍵都被轉換為符號的新雜湊,前提是它們回應 to_sym

hash = { 'name' => 'Rob', 'age' => '28' }

hash.symbolize_keys
# => {:name=>"Rob", :age=>"28"}
別名:to_options
# File activesupport/lib/active_support/core_ext/hash/keys.rb, line 27
def symbolize_keys
  transform_keys { |key| key.to_sym rescue key }
end

symbolize_keys!()

破壞性地將所有鍵轉換為符號,前提是它們回應 to_sym。與 symbolize_keys 相同,但會修改 self

別名:to_options!
# File activesupport/lib/active_support/core_ext/hash/keys.rb, line 34
def symbolize_keys!
  transform_keys! { |key| key.to_sym rescue key }
end

to_options()

to_options!()

to_param(namespace = nil)

別名:to_query

to_query(namespace = nil)

返回一個適用於 URL 查詢字串的接收器字串表示形式

{name: 'David', nationality: 'Danish'}.to_query
# => "name=David&nationality=Danish"

可以傳入一個可選的名稱空間來封裝鍵名

{name: 'David', nationality: 'Danish'}.to_query('user')
# => "user%5Bname%5D=David&user%5Bnationality%5D=Danish"

組成查詢字串的字串對「key=value」按字典順序升序排列。

別名:to_param
# File activesupport/lib/active_support/core_ext/object/to_query.rb, line 75
def to_query(namespace = nil)
  query = filter_map do |key, value|
    unless (value.is_a?(Hash) || value.is_a?(Array)) && value.empty?
      value.to_query(namespace ? "#{namespace}[#{key}]" : key)
    end
  end

  query.sort! unless namespace.to_s.include?("[]")
  query.join("&")
end

to_xml(options = {})

返回一個包含其接收器 XML 表示形式的字串

{ foo: 1, bar: 2 }.to_xml
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <hash>
#   <foo type="integer">1</foo>
#   <bar type="integer">2</bar>
# </hash>

為此,該方法會迴圈遍歷鍵值對,並根據*值*構建節點。給定一個鍵值對 keyvalue

  • 如果 value 是一個雜湊,則會以 key 作為 :root 進行遞迴呼叫。

  • 如果 value 是一個陣列,則會以 key 作為 :root 進行遞迴呼叫,並將 key 單數化作為 :children

  • 如果 value 是一個可呼叫物件,它必須接受一個或兩個參數。根據參數數量,可呼叫物件會以 options 雜湊作為第一個參數,以 key 作為 :root,並將 key 單數化作為第二個參數進行呼叫。可呼叫物件可以使用 options[:builder] 新增節點。

    {foo: lambda { |options, key| options[:builder].b(key) }}.to_xml
    # => "<b>foo</b>"
    
  • 如果 value 回應 to_xml,則會以 key 作為 :root 呼叫該方法。

    class Foo
      def to_xml(options)
        options[:builder].bar 'fooing!'
      end
    end
    
    { foo: Foo.new }.to_xml(skip_instruct: true)
    # =>
    # <hash>
    #   <bar>fooing!</bar>
    # </hash>
    
  • 否則,將會建立一個以 key 作為標籤的節點,並以 value 的字串表示形式作為文字節點。如果 valuenil,則會新增一個屬性「nil」,並將其設定為「true」。除非存在選項 :skip_types 並且其值為 true,否則也會根據以下映射新增一個屬性「type」

    XML_TYPE_NAMES = {
      "Symbol"     => "symbol",
      "Integer"    => "integer",
      "BigDecimal" => "decimal",
      "Float"      => "float",
      "TrueClass"  => "boolean",
      "FalseClass" => "boolean",
      "Date"       => "date",
      "DateTime"   => "dateTime",
      "Time"       => "dateTime"
    }
    

預設情況下,根節點是「hash」,但可以通過 :root 選項進行配置。

預設的 XML 建立器是 Builder::XmlMarkup 的新執行個體。您可以使用 :builder 選項配置您自己的建立器。該方法也接受 :dasherize 等選項,它們會被轉發給建立器。

# File activesupport/lib/active_support/core_ext/hash/conversions.rb, line 74
def to_xml(options = {})
  require "active_support/builder" unless defined?(Builder::XmlMarkup)

  options = options.dup
  options[:indent]  ||= 2
  options[:root]    ||= "hash"
  options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent])

  builder = options[:builder]
  builder.instruct! unless options.delete(:skip_instruct)

  root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options)

  builder.tag!(root) do
    each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options) }
    yield builder if block_given?
  end
end

with_defaults(other_hash)

別名:reverse_merge

with_defaults!(other_hash)

with_indifferent_access()

從其接收器返回一個 ActiveSupport::HashWithIndifferentAccess

{ a: 1 }.with_indifferent_access['a'] # => 1
# File activesupport/lib/active_support/core_ext/hash/indifferent_access.rb, line 9
def with_indifferent_access
  ActiveSupport::HashWithIndifferentAccess.new(self)
end