- D
- E
- F
- I
- S
- T
-
- third,
- third_to_last,
- 到,
- to_formatted_s,
- to_fs,
- to_param,
- to_query,
- 转成句子,
- 转成 XML
- 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会继续尝试to_a,如果返回值是nil,但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。
来源: 显示 | 在 GitHub 上
# 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
来源: 显示 | 在 GitHub 上
# File activesupport/lib/active_support/core_ext/object/deep_dup.rb, line 29 def deep_dup map(&:deep_dup) end
excluding(*elements) 链接
返回一个排除指定元素的数组副本。
["David", "Rafael", "Aaron", "Todd"].excluding("Aaron", "Todd") # => ["David", "Rafael"] [ [ 0, 1 ], [ 1, 0 ] ].excluding([ [ 1, 0 ] ]) # => [ [ 0, 1 ] ]
注意:这是 Enumerable#excluding 的优化,它使用 Array#- 而不是 Array#reject 以提高性能。
来源: 显示 | 在 GitHub 上
# File activesupport/lib/active_support/core_ext/array/access.rb, line 47 def excluding(*elements) self - elements.flatten(1) end
extract!() 链接
移除并返回块返回 true 值的元素。如果未提供块,则返回一个 Enumerator。
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]
来源: 显示 | 在 GitHub 上
# 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}
来源: 显示 | 在 GitHub 上
# 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"
来源: 显示 | 在 GitHub 上
# 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
来源: 显示 | 在 GitHub 上
# 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"
来源: 显示 | 在 GitHub 上
# 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) # => []
来源: 显示 | 在 GitHub 上
# 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, ' ') {|group| p group} ["1", "2", "3", "4"] ["5", "6", "7", " "] ["8", "9", "10", " "] %w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group} ["1", "2", "3"] ["4", "5"] ["6", "7"]
来源: 显示 | 在 GitHub 上
# 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, ' ') {|group| p group} ["1", "2"] ["3", "4"] ["5", " "] %w(1 2 3 4 5).in_groups_of(2, false) {|group| p group} ["1", "2"] ["3", "4"] ["5"]
来源: 显示 | 在 GitHub 上
# 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 ] ]
来源: 显示 | 在 GitHub 上
# 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
来源: 显示 | 在 GitHub 上
# 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"
来源: 显示 | 在 GitHub 上
# 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"
来源: 显示 | 在 GitHub 上
# 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]]
来源: 显示 | 在 GitHub 上
# 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"
来源: 显示 | 在 GitHub 上
# 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"
来源: 显示 | 在 GitHub 上
# 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) # => []
来源: 显示 | 在 GitHub 上
# 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_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]"
来源: 显示 | 在 GitHub 上
# 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() 链接
来源: 显示 | 在 GitHub 上
# File activesupport/lib/active_support/core_ext/object/to_query.rb, line 48 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"
来源: 显示 | 在 GitHub 上
# File activesupport/lib/active_support/core_ext/object/to_query.rb, line 56 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"
来源: 显示 | 在 GitHub 上
# 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>
来源: 显示 | 在 GitHub 上
# 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