Algorithm in Ruby