[Feature #18183] Add chars: option to Random#alphanumeric

This commit is contained in:
Nobuyoshi Nakada 2023-08-29 10:56:56 +09:00
parent c4fc9477aa
commit 7e5c662a6f
No known key found for this signature in database
GPG Key ID: 3582D74E1FEE4465
3 changed files with 28 additions and 3 deletions

View File

@ -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

View File

@ -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

View File

@ -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