Sha256: 7fa2e7e9ccc3548bf5ddacdd91731da544ed3afb23412aa7d6f409b3972c37c1

Contents?: true

Size: 666 Bytes

Versions: 6

Compression:

Stored size: 666 Bytes

Contents

# frozen_string_literal: true

Array.class_eval do
  unless method_defined?(:weighted_sum)
    # Sums the array with each element weighing 10 times as the next.
    # Expects `self` to be [Array<Numeric>]
    #
    # @raise [RubyRailsExtensions::Errors::NonNumericError] if any element is not Numeric
    #
    # @return [Integer]
    #
    def weighted_sum
      each_with_index.sum do |val, index|
        unless Numeric === val
          raise(
            RubyRailsExtensions::Errors::NonNumericError,
            "Wrong element type (given #{val.class}, expected Numeric)"
          )
        end

        val * (10**(size - index))
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
ruby-rails-extensions-1.1.1 lib/ruby-rails-extensions/extensions/weighted_sum.rb
ruby-rails-extensions-1.1.1.pre.rc.1 lib/ruby-rails-extensions/extensions/weighted_sum.rb
ruby-rails-extensions-0.2.0 lib/ruby-rails-extensions/extensions/weighted_sum.rb
ruby-rails-extensions-0.2.0.pre.rc.1 lib/ruby-rails-extensions/extensions/weighted_sum.rb
ruby-rails-extensions-1.1.0 lib/ruby-rails-extensions/extensions/weighted_sum.rb
ruby-rails-extensions-1.1.0.pre.rc.1 lib/ruby-rails-extensions/extensions/weighted_sum.rb