ankane / or-tools-ruby

Operations research tools for Ruby
Apache License 2.0
174 stars 24 forks source link

DEPRECATION WARNING: Rails 7.0 has deprecated Enumerable.sum in favor of Ruby's native implementation available since 2.4. Sum of non-numeric elements requires an initial argument. #56

Closed joegaudet closed 6 months ago

joegaudet commented 6 months ago

Recently updated to the latest OR-Tools, and I'm seeing this dep warning a bunch whenever I sum a collection of variables.

I tried putting an initial value of 0 but it gave me a type coercion error.

Any thoughts?

.joe

ankane commented 6 months ago

Hi @joegaudet, can you share a code example?

joegaudet commented 6 months ago
model = ORTools::CpModel.new
a = model.new_bool_var('a')
b = model.new_bool_var('a')
c = model.new_bool_var('a')
model.add([a,b,c].sum == 1)

But in the context of a rails application, which I assume is doing something with Enumeration#sum, I see from the employee scheduling example that you use model.sum instead of the array primitive, is that recommended?

I tried putting initial values of 0 as suggested by the error message:

model = ORTools::CpModel.new
a = model.new_bool_var('a')
b = model.new_bool_var('a')
c = model.new_bool_var('a')
model.add([a,b,c].sum(0) == 1)

But it failed with the following: /Users/joegaudet/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/activesupport-7.0.8.1/lib/active_support/core_ext/enumerable.rb:318:in `+': ORTools::BoolVar can't be coerced into Integer (TypeError)

ankane commented 6 months ago

Yeah, you'll need to use model.sum([a,b,c]) for the constraint solver.

joegaudet commented 6 months ago

Oh looking at the implementation I can also do the following:

arr.sum(SatLinearExpr.new)
ankane commented 6 months ago

That's an internal detail (which could change at any time), so I wouldn't recommend it.