Суммирование массива

Приведенный ниже код прошел тесты на Ruby 1.8/1.9, но когда я запускаю эти тесты на Ruby 1.9.2, Я не получаю ошибок метода для Array#sum. Например,

NoMethodError: undefined method `sum' for [3.2, 3.0, 1.5, 0.73, 0.47, 0.23]:Array

Я наткнулся на inject(:+), но когда я попытался подставить его вместо sum, это создало другие проблемы. Есть два метода, где используется sum, time_required и balance_queues. Во втором способе было сложно встроить его в старый код q1.sum - q2.sum. Как много деталей/объяснений было бы полезно.

class FairDistribution
  def initialize(jobs, num_of_queues)
    @queues = [ jobs.sort.reverse ]
    (num_of_queues - 1).times { @queues << [] }

    # Balance the queues until they are perfectly balanced
    while !balance_all_queues do; end
  end

  # Time required for all queues processing
  def time_required
    @queues.map { |q| q.sum }.max                      #SUM
  end

  # The actual distribution of jobs across the queues
  def distribution
    @queues
  end

  private

  # Runs through all queues and balances them against each other.
  # Makes one pass only and returns FALSE if there was nothing changed
  # during the pass.
  def balance_all_queues
    updated = false

    @queues.each_with_index do |q1, qi1|
      (qi1+1 ... @queues.size).each do |qi2|
        res = balance_queues(q1, @queues[qi2])
        updated ||= res
      end
    end

    return !updated
  end

  # Balances the two queues between themselves by finding the best possible
  # swap of jobs between them. If there's nothing to be improved, returns FALSE.
  def balance_queues(q1, q2)
    delta =  q1.sum - q2.sum                            #SUM
    return false if delta == 0

    best_swap       = nil
    best_swap_delta = delta.abs

    q1.each_combination do |c1|
      best_swap, best_swap_delta = choose_better_swap(c1, [], delta, best_swap, best_swap_delta)

      q2.each_combination do |c2|
        best_swap, best_swap_delta = choose_better_swap(c1, c2, delta, best_swap, best_swap_delta)
      end
    end

    best_swap.apply(q1, q2) unless best_swap.nil?

    return !best_swap.nil?
  end

  # Sees if the swap we have at hand is better than our current best
  # swap and replaces the latest if it is.
  def choose_better_swap(c1, c2, delta, best_swap, best_swap_delta)
    unless c1 == c2
      s = Swap.new(c1, c2, delta)
      best_swap, best_swap_delta = s, s.delta if s.delta < best_swap_delta 
    end

    return best_swap, best_swap_delta
  end
end

person BrainLikeADullPencil    schedule 16.11.2012    source источник


Ответы (1)


Enumerable#sum предоставляется ActiveSupport (часть Ruby on Rails). Если у вас установлен гем active_support, вы можете использовать [].sum, добавив его в начало скрипта:

require 'active_support/core_ext/enumerable'

Попробуйте использовать .inject(0, :+). Это приведет к '0' для пустого массива и может быть причиной ваших проблем с inject.

person ndbroadbent    schedule 16.11.2012
comment
спасибо, это решило проблему «суммы». Только раскрыть другое. опубликует еще один вопрос, если это необходимо. ваше здоровье - person BrainLikeADullPencil; 17.11.2012
comment
Большой! Также см. мое редактирование о том, почему «сумма» недоступна в простом Ruby. - person ndbroadbent; 17.11.2012
comment
видел это, ценю как можно больше информации. Спасибо. - person BrainLikeADullPencil; 17.11.2012