跳至內容 跳至搜尋
命名空間
方法
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()

使用區塊結果做為鍵值,將可列舉項目轉換成 hash,元素做為數值。

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 } 會傳回 true,如果超過 1 個人年齡大於 26 歲。

# 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