跳至内容 跳至搜索
命名空间
方法
C
E
I
M
P
S
W

实例公共方法

compact_blank()

返回一个新的 Array,不包含空白项。使用 Object#blank? 来判断一个项是否为空白。

[1, "", nil, 2, " ", [], {}, false, true].compact_blank
# =>  [1, 2, true]

Set.new([nil, "", 1, false]).compact_blank
# => [1]

当在 Hash 上调用时,返回一个新的 Hash,不包含空白值。

{ a: "", b: 1, c: nil, d: [], e: false, f: true }.compact_blank
# => { b: 1, f: true }
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 184
def compact_blank
  reject(&:blank?)
end

exclude?(object)

Enumerable#include? 的否定形式。如果集合不包含该对象,则返回 true

# File activesupport/lib/active_support/core_ext/enumerable.rb, line 118
def exclude?(object)
  !include?(object)
end

excluding(*elements)

返回一个不包含指定元素的可枚举副本。

["David", "Rafael", "Aaron", "Todd"].excluding "Aaron", "Todd"
# => ["David", "Rafael"]

["David", "Rafael", "Aaron", "Todd"].excluding %w[ Aaron Todd ]
# => ["David", "Rafael"]

{foo: 1, bar: 2, baz: 3}.excluding :bar
# => {foo: 1, baz: 3}
也称为: without
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 132
def excluding(*elements)
  elements.flatten!(1)
  reject { |element| elements.include?(element) }
end

in_order_of(key, series, filter: true)

返回一个新的 Array,其中顺序已设置为 series 中提供的顺序,基于原始可枚举中对象的 key

[ Person.find(5), Person.find(3), Person.find(1) ].in_order_of(:id, [ 1, 5, 3 ])
# => [ Person.find(1), Person.find(5), Person.find(3) ]

如果 series 包含在 Enumerable 中没有对应元素的键,则会忽略这些键。如果 Enumerable 有额外的元素未在 series 中命名,则这些元素不会包含在结果中,除非 filter 选项设置为 false

# File activesupport/lib/active_support/core_ext/enumerable.rb, line 197
def in_order_of(key, series, filter: true)
  if filter
    group_by(&key).values_at(*series).flatten(1).compact
  else
    sort_by { |v| series.index(v.public_send(key)) || series.size }.compact
  end
end

including(*elements)

返回一个包含传入元素的新数组。

[ 1, 2, 3 ].including(4, 5)
# => [ 1, 2, 3, 4, 5 ]

["David", "Rafael"].including %w[ Aaron Todd ]
# => ["David", "Rafael", "Aaron", "Todd"]
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 112
def including(*elements)
  to_a.including(*elements)
end

index_by()

将一个可枚举转换为一个哈希,使用块结果作为键,元素作为值。

people.index_by(&:login)
# => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...}

people.index_by { |person| "#{person.first_name} #{person.last_name}" }
# => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...}
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 52
def index_by
  if block_given?
    result = {}
    each { |elem| result[yield(elem)] = elem }
    result
  else
    to_enum(:index_by) { size if respond_to?(:size) }
  end
end

index_with(default = (no_default = true))

将一个可枚举转换为一个哈希,使用元素作为键,块结果作为值。

post = Post.new(title: "hey there", body: "what's up?")

%i( title body ).index_with { |attr_name| post.public_send(attr_name) }
# => { title: "hey there", body: "what's up?" }

如果传递一个参数而不是一个块,它将被用作所有元素的值

%i( created_at updated_at ).index_with(Time.now)
# => { created_at: 2020-03-09 22:31:47, updated_at: 2020-03-09 22:31:47 }
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 75
def index_with(default = (no_default = true))
  if block_given?
    result = {}
    each { |elem| result[elem] = yield(elem) }
    result
  elsif no_default
    to_enum(:index_with) { size if respond_to?(:size) }
  else
    result = {}
    each { |elem| result[elem] = default }
    result
  end
end

many?()

如果可枚举元素超过 1 个,则返回 true。在功能上等效于 enum.to_a.size > 1。也可以使用块调用,类似于 any?,所以 people.many? { |p| p.age > 26 } 如果超过一个人的年龄超过 26 岁,则返回 true

# File activesupport/lib/active_support/core_ext/enumerable.rb, line 93
def many?
  cnt = 0
  if block_given?
    any? do |*args|
      cnt += 1 if yield(*args)
      cnt > 1
    end
  else
    any? { (cnt += 1) > 1 }
  end
end

maximum(key)

从提取的元素中计算最大值。

payments = [Payment.new(5), Payment.new(15), Payment.new(10)]
payments.maximum(:price) # => 15
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 40
def maximum(key)
  map(&key).max
end

minimum(key)

从提取的元素中计算最小值。

payments = [Payment.new(5), Payment.new(15), Payment.new(10)]
payments.minimum(:price) # => 5
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 32
def minimum(key)
  map(&key).min
end

pick(*keys)

从可枚举中的第一个元素中提取给定的键。

[{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pick(:name)
# => "David"

[{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pick(:id, :name)
# => [1, "David"]
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 161
def pick(*keys)
  return if none?

  if keys.many?
    keys.map { |key| first[key] }
  else
    first[keys.first]
  end
end

pluck(*keys)

从可枚举中的每个元素中提取给定的键。

[{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pluck(:name)
# => ["David", "Rafael", "Aaron"]

[{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pluck(:id, :name)
# => [[1, "David"], [2, "Rafael"]]
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 145
def pluck(*keys)
  if keys.many?
    map { |element| keys.map { |key| element[key] } }
  else
    key = keys.first
    map { |element| element[key] }
  end
end

sole()

返回可枚举中的唯一项。如果没有项,或超过一个项,则会抛出 Enumerable::SoleItemExpectedError 错误。

["x"].sole          # => "x"
Set.new.sole        # => Enumerable::SoleItemExpectedError: no item found
{ a: 1, b: 2 }.sole # => Enumerable::SoleItemExpectedError: multiple items found
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 211
def sole
  case count
  when 1   then return first # rubocop:disable Style/RedundantReturn
  when 0   then raise ActiveSupport::EnumerableCoreExt::SoleItemExpectedError, "no item found"
  when 2.. then raise ActiveSupport::EnumerableCoreExt::SoleItemExpectedError, "multiple items found"
  end
end

without(*elements)

别名: excluding