From 13ecf3ed4d5867c593ccb9c656288961b6ed885f Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Tue, 24 Aug 2021 19:22:01 +0900 Subject: [PATCH] Allow no separator --- lib/random/formatter.rb | 30 ++++++++++++++++++++++-------- test/ruby/test_random_formatter.rb | 3 +++ 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/lib/random/formatter.rb b/lib/random/formatter.rb index 6762355..883b0b1 100644 --- a/lib/random/formatter.rb +++ b/lib/random/formatter.rb @@ -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 @@ -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 diff --git a/test/ruby/test_random_formatter.rb b/test/ruby/test_random_formatter.rb index 81999fe..87be445 100644 --- a/test/ruby/test_random_formatter.rb +++ b/test/ruby/test_random_formatter.rb @@ -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)