跳至内容 跳至搜索
方法
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,则调用该方法。Kernel#Array 如果返回值是nil,则继续尝试to_a,但Array.wrap立即返回一个带有参数作为其单个元素的数组。

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

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

最后一点用一些枚举来解释

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_with填充任何剩余的插槽,除非它是false

%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_with填充任何剩余的插槽,除非它是false

%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 - 用于连接三个或更多元素的数组中最后一个元素的符号或单词(默认值:“,和 ”)。

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

  • :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 183
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