Created: 2008-06-20 09:58
Updated: 2018-05-28 08:31

gga4r - General Genetic Algorithm for Ruby


General Genetic Algorithm for Ruby is a Ruby Genetic Algorithm that is very simple to use:

  1. Take a class to evolve it and define fitness, recombine and mutate methods.
class StringPopulation < Array
  def fitness { |pos| pos == 1 }.size.to_f / self.size.to_f

  def recombine(c2)
    cross_point = (rand * c2.size).to_i
    c1_a, c1_b = self.separate(cross_point)
    c2_a, c2_b = c2.separate(cross_point) + c2_b)

  def mutate
    mutate_point = (rand * self.size).to_i
    self[mutate_point] = 1
  1. Create a GeneticAlgorithm object with the population.
def create_population_with_fit_all_1s(s_long = 10, num = 10)
    population = []
    num.times  do
      chromosome = { (rand > 0.2) ? 0:1 })
      population << chromosome

ga =
  1. Call the evolve method as many times as you want and see the best evolution.
100.times { |i|  ga.evolve }
p ga.best_fit[0]


  1. Execute:
gem install gga4r
  1. Add require in your code headers:
require "rubygems"
require "gga4r"


Documentation can be generated using rdoc tool under the source code with:

rdoc README lib



This work is developed by Sergio Espeja (, sergio.espeja at ) mainly in Institut Universitari de Lingüística Aplicada of Universitat Pompeu Fabra ( ), and also in ( ).

It is free software, and may be redistributed under GPL license.

Cookies help us deliver our services. By using our services, you agree to our use of cookies Learn more