algorithm in ruby