diff options
-rw-r--r-- | NEWS.md | 4 | ||||
-rw-r--r-- | lib/random/formatter.rb | 13 | ||||
-rw-r--r-- | test/ruby/test_random_formatter.rb | 14 |
3 files changed, 28 insertions, 3 deletions
@@ -64,6 +64,9 @@ Note: We're only listing outstanding class updates. ## Stdlib updates +* Random::Formatter#alphanumeric is extended to accept optional `chars` + keyword argument. [[Feature #18183]] + The following default gems are updated. * RubyGems 3.5.0.dev @@ -156,6 +159,7 @@ changelog for details of the default gems or bundled gems. * RJIT exists only for experimental purposes. * You should keep using YJIT in production. +[Feature #18183]: https://bugs.ruby-lang.org/issues/18183 [Feature #18498]: https://bugs.ruby-lang.org/issues/18498 [Feature #18885]: https://bugs.ruby-lang.org/issues/18885 [Bug #19150]: https://bugs.ruby-lang.org/issues/19150 diff --git a/lib/random/formatter.rb b/lib/random/formatter.rb index 4dea61c16c..18e6717b6c 100644 --- a/lib/random/formatter.rb +++ b/lib/random/formatter.rb @@ -226,11 +226,13 @@ module Random::Formatter # # The argument _n_ specifies the length, in characters, of the alphanumeric # string to be generated. + # The argument _chars_ specifies the character list which the result is + # consist of. # # If _n_ is not specified or is nil, 16 is assumed. # It may be larger in the future. # - # The result may contain A-Z, a-z and 0-9. + # The result may contain A-Z, a-z and 0-9, unless _chars_ is specified. # # require 'random/formatter' # @@ -238,8 +240,13 @@ module Random::Formatter # # or # prng = Random.new # prng.alphanumeric(10) #=> "i6K93NdqiH" - def alphanumeric(n=nil) + # + # Random.alphanumeric(4, chars: [*"0".."9"])' #=> "2952" + # # or + # prng = Random.new + # prng.alphanumeric(10, chars: [*"!".."/"]) #=> ",.,++%/''." + def alphanumeric(n = nil, chars: ALPHANUMERIC) n = 16 if n.nil? - choose(ALPHANUMERIC, n) + choose(chars, n) end end diff --git a/test/ruby/test_random_formatter.rb b/test/ruby/test_random_formatter.rb index a5072099e1..2c01d99b3d 100644 --- a/test/ruby/test_random_formatter.rb +++ b/test/ruby/test_random_formatter.rb @@ -83,6 +83,20 @@ module Random::Formatter end end + def test_alphanumeric_chars + [ + [[*"0".."9"], /\A\d*\z/], + [[*"a".."t"], /\A[a-t]*\z/], + ["一二三四五六七八九十".chars, /\A[一二三四五六七八九十]*\z/], + ].each do |chars, pattern| + 10.times do |n| + an = @it.alphanumeric(n, chars: chars) + assert_match(pattern, an) + assert_equal(n, an.length) + end + end + end + def assert_in_range(range, result, mesg = nil) assert(range.cover?(result), build_message(mesg, "Expected #{result} to be in #{range}")) end |