diff --git a/lib/faker.rb b/lib/faker.rb index a5d7d472b9..c0c5708541 100644 --- a/lib/faker.rb +++ b/lib/faker.rb @@ -58,6 +58,9 @@ class Base ULetters = Array('A'..'Z') LLetters = Array('a'..'z') Letters = ULetters + LLetters + # Frozen digit strings, used to avoid allocating a new string for each + # random digit generated by #numerify. + DIGITS = %w[0 1 2 3 4 5 6 7 8 9].freeze class << self attr_reader :flexible_key @@ -66,9 +69,15 @@ class << self ## by default numerify results do not start with a zero def numerify(number_string, leading_zero: false) - return number_string.gsub('#') { rand(10).to_s } if leading_zero - - number_string.sub('#') { rand(1..9).to_s }.gsub('#') { rand(10).to_s } + leading = !leading_zero + number_string.gsub('#') do + if leading + leading = false + DIGITS[rand(1..9)] + else + DIGITS[rand(10)] + end + end end def letterify(letter_string)