Constraint Programming in Ruby

Gecode/R is a Ruby interface to Gecode, an open source library for constraint programming. The interface is intended for people with no previous experience of constraint programming, aiming to be easy to pick up and use in practice.

Describe Your Problem

Constraint programming is declarative. Describe your problem to the solver and then let it find solutions for you.


Solve the equation system x + y = z, x = y - 3, 0 <= x,y,z <= 9.

solution = Gecode.solve do
  # Set up the variables, three integers with domain 0..9.
  variables_is_an int_var_array(3, 0..9) 
  x,y,z = variables

  # Describe the problem (in this case the equations).
  (x + y).must == z 
  x.must == y - 3

  # Tell it what the variables of the problem are.
  branch_on variables

puts 'x y z'
puts solution.variables.values.join(' ')


x y z
0 3 3

Constraint programming is an easy way to solve problems that are simpler to describe than to solve. Sudoku is one of many examples.