跳至内容 跳至搜索
方法
A
C
D
E
F
N
R
S
T
W

类公共方法

from_trusted_xml(xml)

从 XML 构建一个 哈希,就像 Hash.from_xml,但还允许 符号 和 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)

返回一个 哈希,其中包含一组对,其中键是节点名称,值是其内容

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"

请注意,传递自定义不允许的类型会覆盖默认类型,即 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

实例公共方法

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 227
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)

返回一个新的哈希,其中 selfother_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(&: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!(&: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.except(:a, :b) # => { c: nil }
hash                # => { a: true, b: false, c: nil }

这对于将一组参数限制为除几个已知切换之外的所有内容非常有用

@person.update(params[:person].except(:admin))
# File activesupport/lib/active_support/core_ext/hash/except.rb, line 12
def except(*keys)
  slice(*self.keys - keys)
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 20
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 可提取,当 HashArray 的最后一个元素时,Array#extract_options! 会从 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_accessHash 的子类可以覆盖此方法以返回 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

也别名为:reverse_updatewith_defaults!
# 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)

别名:reverse_merge!

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(&: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!(&: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()

别名:symbolize_keys

to_options!()

别名:symbolize_keys!

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作为:rootkey单数形式作为: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)

别名:reverse_merge!

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