跳至内容 跳至搜索
方法
D
E
F
I
S
T
W

类公有方法

wrap(object)

将参数包装在数组中,除非它已经是数组(或类似数组)。

具体来说

  • 如果参数为 nil,则返回一个空数组。

  • 否则,如果参数响应 to_ary,则调用它并返回其结果。

  • 否则,返回一个数组,其中参数作为其单个元素。

    Array.wrap(nil)       # => []
    Array.wrap([1, 2, 3]) # => [1, 2, 3]
    Array.wrap(0)         # => [0]
    

此方法在目的上类似于 Kernel#Array,但有一些区别

  • 如果参数响应 to_ary,则调用该方法。如果返回的值为 nil,则 Kernel#Array 继续尝试 to_a,但 Array.wrap 立即返回一个数组,其中参数作为其单个元素。

  • 如果 to_ary 的返回值既不是 nil 也不是 Array 对象,则 Kernel#Array 会引发异常,而 Array.wrap 不会,它只会返回该值。

  • 如果参数不响应 to_ary,它不会在参数上调用 to_a,它会返回一个数组,其中参数作为其单个元素。

最后一点很容易用一些枚举解释

Array(foo: :bar)      # => [[:foo, :bar]]
Array.wrap(foo: :bar) # => [{:foo=>:bar}]

还有一种相关的习语,它使用展开运算符

[*object]

它为 nil 返回 [],但否则调用 Array(object)

上面解释的 Kernel#Array 的差异适用于 object 的其余部分。

# File activesupport/lib/active_support/core_ext/array/wrap.rb, line 39
def self.wrap(object)
  if object.nil?
    []
  elsif object.respond_to?(:to_ary)
    object.to_ary || [object]
  else
    [object]
  end
end

实例公共方法

deep_dup()

返回数组的深度副本。

array = [1, [2, 3]]
dup   = array.deep_dup
dup[1][2] = 4

array[1][2] # => nil
dup[1][2]   # => 4
# File activesupport/lib/active_support/core_ext/object/deep_dup.rb, line 29
def deep_dup
  map(&:deep_dup)
end

excluding(*elements)

返回不包含指定元素的 Array 的副本。

["David", "Rafael", "Aaron", "Todd"].excluding("Aaron", "Todd") # => ["David", "Rafael"]
[ [ 0, 1 ], [ 1, 0 ] ].excluding([ [ 1, 0 ] ]) # => [ [ 0, 1 ] ]

注意:这是 Enumerable#excluding 的优化,出于性能原因,它使用 Array#- 而不是 Array#reject

别名:without
# File activesupport/lib/active_support/core_ext/array/access.rb, line 47
def excluding(*elements)
  self - elements.flatten(1)
end

extract!()

移除并返回满足块条件的元素。如果没有提供块,则返回一个枚举器。

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
odd_numbers = numbers.extract! { |number| number.odd? } # => [1, 3, 5, 7, 9]
numbers # => [0, 2, 4, 6, 8]
# File activesupport/lib/active_support/core_ext/array/extract.rb, line 10
def extract!
  return to_enum(:extract!) { size } unless block_given?

  extracted_elements = []

  reject! do |element|
    extracted_elements << element if yield(element)
  end

  extracted_elements
end

extract_options!()

从一组参数中提取选项。如果数组中的最后一个元素是哈希,则移除并返回该元素,否则返回一个空哈希。

def options(*args)
  args.extract_options!
end

options(1, 2)        # => {}
options(1, 2, a: :b) # => {:a=>:b}
# File activesupport/lib/active_support/core_ext/array/extract_options.rb, line 24
def extract_options!
  if last.is_a?(Hash) && last.extractable_options?
    pop
  else
    {}
  end
end

fifth()

等于 self[4]

%w( a b c d e ).fifth # => "e"
# File activesupport/lib/active_support/core_ext/array/access.rb, line 76
def fifth
  self[4]
end

forty_two()

等于 self[41]。也称为访问“reddit”。

(1..42).to_a.forty_two # => 42
# File activesupport/lib/active_support/core_ext/array/access.rb, line 83
def forty_two
  self[41]
end

fourth()

等于 self[3]

%w( a b c d e ).fourth # => "d"
# File activesupport/lib/active_support/core_ext/array/access.rb, line 69
def fourth
  self[3]
end

from(position)

position 返回数组的尾部。

%w( a b c d ).from(0)  # => ["a", "b", "c", "d"]
%w( a b c d ).from(2)  # => ["c", "d"]
%w( a b c d ).from(10) # => []
%w().from(0)           # => []
%w( a b c d ).from(-2) # => ["c", "d"]
%w( a b c ).from(-10)  # => []
# File activesupport/lib/active_support/core_ext/array/access.rb, line 12
def from(position)
  self[position, length] || []
end

in_groups(number, fill_with = nil, &block)

number 个组中拆分或迭代数组,除非 fill_withfalse,否则用 fill_with 填充任何剩余的槽位。

%w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group}
["1", "2", "3", "4"]
["5", "6", "7", nil]
["8", "9", "10", nil]

%w(1 2 3 4 5 6 7 8 9 10).in_groups(3, '&nbsp;') {|group| p group}
["1", "2", "3", "4"]
["5", "6", "7", "&nbsp;"]
["8", "9", "10", "&nbsp;"]

%w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group}
["1", "2", "3"]
["4", "5"]
["6", "7"]
# File activesupport/lib/active_support/core_ext/array/grouping.rb, line 62
def in_groups(number, fill_with = nil, &block)
  # size.div number gives minor group size;
  # size % number gives how many objects need extra accommodation;
  # each group hold either division or division + 1 items.
  division = size.div number
  modulo = size % number

  # create a new array avoiding dup
  groups = []
  start = 0

  number.times do |index|
    length = division + (modulo > 0 && modulo > index ? 1 : 0)
    groups << last_group = slice(start, length)
    last_group << fill_with if fill_with != false &&
      modulo > 0 && length == division
    start += length
  end

  if block_given?
    groups.each(&block)
  else
    groups
  end
end

in_groups_of(number, fill_with = nil, &block)

在大小为 number 的组中拆分或迭代数组,除非 fill_withfalse,否则用 fill_with 填充任何剩余的槽位。

%w(1 2 3 4 5 6 7 8 9 10).in_groups_of(3) {|group| p group}
["1", "2", "3"]
["4", "5", "6"]
["7", "8", "9"]
["10", nil, nil]

%w(1 2 3 4 5).in_groups_of(2, '&nbsp;') {|group| p group}
["1", "2"]
["3", "4"]
["5", "&nbsp;"]

%w(1 2 3 4 5).in_groups_of(2, false) {|group| p group}
["1", "2"]
["3", "4"]
["5"]
# File activesupport/lib/active_support/core_ext/array/grouping.rb, line 22
def in_groups_of(number, fill_with = nil, &block)
  if number.to_i <= 0
    raise ArgumentError,
      "Group size must be a positive integer, was #{number.inspect}"
  end

  if fill_with == false
    collection = self
  else
    # size % number gives how many extra we have;
    # subtracting from number gives how many to add;
    # modulo number ensures we don't add group of just fill.
    padding = (number - size % number) % number
    collection = dup.concat(Array.new(padding, fill_with))
  end

  if block_given?
    collection.each_slice(number, &block)
  else
    collection.each_slice(number).to_a
  end
end

including(*elements)

返回包含传递元素的新数组。

[ 1, 2, 3 ].including(4, 5) # => [ 1, 2, 3, 4, 5 ]
[ [ 0, 1 ] ].including([ [ 1, 0 ] ]) # => [ [ 0, 1 ], [ 1, 0 ] ]
# File activesupport/lib/active_support/core_ext/array/access.rb, line 36
def including(*elements)
  self + elements.flatten(1)
end

inquiry()

将数组包装在 ActiveSupport::ArrayInquirer 对象中,该对象提供了一种更友好的方式来检查其类似字符串的内容。

pets = [:cat, :dog].inquiry

pets.cat?     # => true
pets.ferret?  # => false

pets.any?(:cat, :ferret)  # => true
pets.any?(:ferret, :alligator)  # => false
# File activesupport/lib/active_support/core_ext/array/inquiry.rb, line 16
def inquiry
  ActiveSupport::ArrayInquirer.new(self)
end

second()

等于 self[1]

%w( a b c d e ).second # => "b"
# File activesupport/lib/active_support/core_ext/array/access.rb, line 55
def second
  self[1]
end

second_to_last()

等于 self[-2]

%w( a b c d e ).second_to_last # => "d"
# File activesupport/lib/active_support/core_ext/array/access.rb, line 97
def second_to_last
  self[-2]
end

split(value = nil, &block)

根据分隔符 value 或可选代码块的结果将数组划分为一个或多个子数组。

[1, 2, 3, 4, 5].split(3)              # => [[1, 2], [4, 5]]
(1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]]
# File activesupport/lib/active_support/core_ext/array/grouping.rb, line 93
def split(value = nil, &block)
  arr = dup
  result = []
  if block_given?
    while (idx = arr.index(&block))
      result << arr.shift(idx)
      arr.shift
    end
  else
    while (idx = arr.index(value))
      result << arr.shift(idx)
      arr.shift
    end
  end
  result << arr
end

third()

等于 self[2]

%w( a b c d e ).third # => "c"
# File activesupport/lib/active_support/core_ext/array/access.rb, line 62
def third
  self[2]
end

third_to_last()

等于 self[-3]

%w( a b c d e ).third_to_last # => "c"
# File activesupport/lib/active_support/core_ext/array/access.rb, line 90
def third_to_last
  self[-3]
end

to(position)

返回数组开头到 position 的部分。

%w( a b c d ).to(0)  # => ["a"]
%w( a b c d ).to(2)  # => ["a", "b", "c"]
%w( a b c d ).to(10) # => ["a", "b", "c", "d"]
%w().to(0)           # => []
%w( a b c d ).to(-2) # => ["a", "b", "c"]
%w( a b c ).to(-10)  # => []
# File activesupport/lib/active_support/core_ext/array/access.rb, line 24
def to(position)
  if position >= 0
    take position + 1
  else
    self[0..position]
  end
end

to_formatted_s(format = :default)

别名: to_fs

to_fs(format = :default)

扩展 Array#to_s,如果将 :db 参数作为格式提供,则将元素集合转换为逗号分隔的 ID 列表。

此方法的别名为 to_formatted_s

Blog.all.to_fs(:db)  # => "1,2,3"
Blog.none.to_fs(:db) # => "null"
[1,2].to_fs          # => "[1, 2]"
还别名为: to_formatted_s
# File activesupport/lib/active_support/core_ext/array/conversions.rb, line 94
def to_fs(format = :default)
  case format
  when :db
    if empty?
      "null"
    else
      collect(&:id).join(",")
    end
  else
    to_s
  end
end

to_param()

对所有元素调用 to_param 并用斜杠连接结果。Action Pack 中的 url_for 使用此方法。

# File activesupport/lib/active_support/core_ext/object/to_query.rb, line 42
def to_param
  collect(&:to_param).join "/"
end

to_query(key)

将数组转换为适合用作 URL 查询字符串的字符串,使用给定的 key 作为参数名称。

['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding"
# File activesupport/lib/active_support/core_ext/object/to_query.rb, line 50
def to_query(key)
  prefix = "#{key}[]"

  if empty?
    nil.to_query(prefix)
  else
    collect { |value| value.to_query(prefix) }.join "&"
  end
end

to_sentence(options = {})

将数组转换为逗号分隔的句子,其中最后一个元素由连接词连接。

你可以传递以下选项来更改默认行为。如果你传递的选项键在下面的列表中不存在,它将引发 ArgumentError

选项

  • :words_connector - 用于连接数组中除最后一个元素之外所有元素的符号或单词(默认值:“, ”)。

  • :last_word_connector - 用于连接数组中最后一个元素的符号或单词(默认值:“, and ”)。

  • :two_words_connector - 用于连接包含两个元素的数组中的元素的符号或单词(默认值:“ and ”)。

  • :locale - 如果 i18n 可用,你可以设置语言环境并使用在对应词典文件中“support.array”命名空间中定义的连接器选项。

示例

[].to_sentence                      # => ""
['one'].to_sentence                 # => "one"
['one', 'two'].to_sentence          # => "one and two"
['one', 'two', 'three'].to_sentence # => "one, two, and three"

['one', 'two'].to_sentence(passing: 'invalid option')
# => ArgumentError: Unknown key: :passing. Valid keys are: :words_connector, :two_words_connector, :last_word_connector, :locale

['one', 'two'].to_sentence(two_words_connector: '-')
# => "one-two"

['one', 'two', 'three'].to_sentence(words_connector: ' or ', last_word_connector: ' or at least ')
# => "one or two or at least three"

使用 :locale 选项

# Given this locale dictionary:
#
#   es:
#     support:
#       array:
#         words_connector: " o "
#         two_words_connector: " y "
#         last_word_connector: " o al menos "

['uno', 'dos'].to_sentence(locale: :es)
# => "uno y dos"

['uno', 'dos', 'tres'].to_sentence(locale: :es)
# => "uno o dos o al menos tres"
# File activesupport/lib/active_support/core_ext/array/conversions.rb, line 60
def to_sentence(options = {})
  options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale)

  default_connectors = {
    words_connector: ", ",
    two_words_connector: " and ",
    last_word_connector: ", and "
  }
  if options[:locale] != false && defined?(I18n)
    i18n_connectors = I18n.translate(:'support.array', locale: options[:locale], default: {})
    default_connectors.merge!(i18n_connectors)
  end
  options = default_connectors.merge!(options)

  case length
  when 0
    +""
  when 1
    +"#{self[0]}"
  when 2
    +"#{self[0]}#{options[:two_words_connector]}#{self[1]}"
  else
    +"#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}"
  end
end

to_xml(options = {})

返回一个字符串,该字符串通过对每个元素调用 to_xml 来表示 XML 中的数组。Active Record 集合将它们在 XML 中的表示委托给此方法。

预期所有元素响应 to_xml,如果任何元素未响应,则会引发异常。

如果所有元素都属于同一种类型且该类型不是 Hash,则根节点反映复数形式中第一个元素的类名

customer.projects.to_xml

<?xml version="1.0" encoding="UTF-8"?>
<projects type="array">
  <project>
    <amount type="decimal">20000.0</amount>
    <customer-id type="integer">1567</customer-id>
    <deal-date type="date">2008-04-09</deal-date>
    ...
  </project>
  <project>
    <amount type="decimal">57230.0</amount>
    <customer-id type="integer">1567</customer-id>
    <deal-date type="date">2008-04-15</deal-date>
    ...
  </project>
</projects>

否则,根元素为“objects”

[{ foo: 1, bar: 2}, { baz: 3}].to_xml

<?xml version="1.0" encoding="UTF-8"?>
<objects type="array">
  <object>
    <bar type="integer">2</bar>
    <foo type="integer">1</foo>
  </object>
  <object>
    <baz type="integer">3</baz>
  </object>
</objects>

如果集合为空,则根元素默认为“nil-classes”

[].to_xml

<?xml version="1.0" encoding="UTF-8"?>
<nil-classes type="array"/>

要确保根元素有意义,请使用 :root 选项

customer_with_no_projects.projects.to_xml(root: 'projects')

<?xml version="1.0" encoding="UTF-8"?>
<projects type="array"/>

默认情况下,根子节点的节点名称为 root.singularize。您可以使用 :children 选项更改它。

options 哈希向下传递

Message.all.to_xml(skip_types: true)

<?xml version="1.0" encoding="UTF-8"?>
<messages>
  <message>
    <created-at>2008-03-07T09:58:18+01:00</created-at>
    <id>1</id>
    <name>1</name>
    <updated-at>2008-03-07T09:58:18+01:00</updated-at>
    <user-id>1</user-id>
  </message>
</messages>
# File activesupport/lib/active_support/core_ext/array/conversions.rb, line 185
def to_xml(options = {})
  require "active_support/builder" unless defined?(Builder::XmlMarkup)

  options = options.dup
  options[:indent]  ||= 2
  options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent])
  options[:root]    ||= \
    if first.class != Hash && all?(first.class)
      underscored = ActiveSupport::Inflector.underscore(first.class.name)
      ActiveSupport::Inflector.pluralize(underscored).tr("/", "_")
    else
      "objects"
    end

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

  root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options)
  children = options.delete(:children) || root.singularize
  attributes = options[:skip_types] ? {} : { type: "array" }

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

without(*elements)

别名: excluding