baerlein baerlein - 6 months ago 22
Ruby Question

Refactoring random number generation

As I'm learning Ruby I wrote this little program to generate a "nice" number randomly (like 4747, 6969, etc.).
As I'm currently breaking the "do not repeat yourself" rule, how would you refactor the following?

def nice_numbers
a = rand(9)
b = rand(9)
c = rand(9)
d = rand(9)
while a != c || b != d
a = rand(9)
b = rand(9)
c = rand(9)
d = rand(9)
end
nice = [a,b,c,d].join
end

puts nice_numbers

Answer

The code:

def nice_numbers
  ([rand(9),rand(9)]*2).join
end

generates the same output as your function. It is also faster, as it does not test then regenerate anything.

If you want to DRY this up for rand(9):

def nice_numbers
  (Array.new(2) {rand(9)} * 2).join
end

Ruby language features used in this last example:

  • Array constructor takes a size param and a block to fill the Array

  • Multiplying an array by an integer repeats the array

Comments