Skip to content

Commit

Permalink
Allow no separator
Browse files Browse the repository at this point in the history
  • Loading branch information
nobu committed Dec 29, 2023
1 parent 115f2c9 commit 1f9ca50
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
30 changes: 22 additions & 8 deletions lib/random/formatter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,13 @@ def alphanumeric(n = nil, chars: ALPHANUMERIC)
#
# prng.phrase #=> "kDc9y^Xyii4.rm3WB~MAgl0^pSOBn^jsQKc^WakTU!OjfSs"
# prng.phrase(20) #=> "rKz4p-QihCf.zHff4^ukRGn"
#
# If _separators_ is +nil+ or empty, the result will consist of only
# one chunk without separators.
#
# require 'random/formatter'
#
# prng.phrase(10, separators: nil) #=> "YAzMKLQT8G"
def phrase(n = 40, chunk: CHUNK_SIZE, separators: PUNCT, exclude: EXCLUDE)
raise ArgumentError, "invalid chunk size" unless chunk > 0
case n
Expand All @@ -421,15 +428,22 @@ def phrase(n = 40, chunk: CHUNK_SIZE, separators: PUNCT, exclude: EXCLUDE)
when String
separators = separators.chars
end
if separators.size > 1
sep = proc {choose(separators, 1)}
else
sep = proc {separators[0]}
if separators
case
when separators.size > 1
sep = proc {choose(separators, 1)}
when separators.size > 0
sep = proc {separators[0]}
end
end
w, d = n.divmod(chunk + 1)
if d.zero? and w > 1
w -= 1
d = chunk + 1
if sep
w, d = n.divmod(chunk + 1)
if d.zero? and w > 1
w -= 1
d = chunk + 1
end
else
w, d = 0, n
end
source = ALPHANUMERIC
source -= exclude if exclude
Expand Down
3 changes: 3 additions & 0 deletions test/ruby/test_random_formatter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,9 @@ def test_phrase
s.scan(/\w+/) do |c|
assert_operator(c.size, :<=, formatter::CHUNK_SIZE)
end

s = @it.phrase(10, separators: nil)
assert_match(/\A\w{10}\z/, s)
end

def assert_in_range(range, result, mesg = nil)
Expand Down

0 comments on commit 1f9ca50

Please sign in to comment.