модуль Enumerable
Общедоступные методы экземпляров
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 60 def exclude?(object) !include?(object) end
Отрицание Enumerable#include?. Возвращает true если коллекция не содержит объект.
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 34
def index_by
if block_given?
Hash[map { |elem| [yield(elem), elem] }]
else
to_enum(:index_by) { size if respond_to?(:size) }
end
end Преобразование перечислимого объекта в хеш.
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 46
def many?
cnt = 0
if block_given?
any? do |element|
cnt += 1 if yield element
cnt > 1
end
else
any? { (cnt += 1) > 1 }
end
end Возвращает true если перечисляемый объект содержит более одного элемента. Функционально эквивалентно enum.to_a.size > 1. Можно использовать с блоком, аналогично any?, поэтому people.many? { |p| p.age
> 26 } возвращает true если больше одного человека старше 26 лет.
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 20
def sum(identity = 0, &block)
if block_given?
map(&block).sum(identity)
else
inject { |sum, element| sum + element } || identity
end
end Вычисление суммы элементов.
payments.sum { |p| p.price * p.tax_rate }
payments.sum(&:price)
Последнее — это сокращение для:
payments.inject(0) { |sum, p| sum + p.price }
Также можно вычислить сумму без использования блока.
[5, 15, 10].sum # => 30 ['foo', 'bar'].sum # => "foobar" [[1, 2], [3, 1, 5]].sum => [1, 2, 3, 1, 5]
По умолчанию сумма пустого списка равна нулю. Вы можете изменить это значение:
[].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
© 2004–2018 David Heinemeier Hansson
Licensed under the MIT License.