public
Created

  • Download Gist
random_phones.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#
# generates a random phone number by generating a random set
#
require 'set'
 
class RandomPhone
PHONE_MAP = []
 
def self.number
nums = rand_n(10, 10)
"#{nums[0..2].join}-#{nums[3..5].join}-#{nums[6..9].join}"
end
 
protected
 
def self.rand_n(n, max)
randoms = []
 
loop do
break randoms = gen_rand(n, max)
end while PHONE_MAP.include?(randoms.join) or randoms.empty?
 
PHONE_MAP << randoms.join
return randoms
end
 
def self.gen_rand(n, max)
randoms = Set.new
 
loop do
randoms << rand(max)
return randoms.to_a if randoms.size >= n
end
end
end

This isn't perfect but fit the need, don't use this in your app code unless you like memory growing outrageously.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.