From 0a0e977b7c0dd2df42853e60aabdf67eef045755 Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Sun, 9 Mar 2025 22:54:21 +0900 Subject: [PATCH 1/2] Add test for enum arguments --- test/optparse/test_placearg.rb | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test/optparse/test_placearg.rb b/test/optparse/test_placearg.rb index a8a11e6..c6dc7ab 100644 --- a/test/optparse/test_placearg.rb +++ b/test/optparse/test_placearg.rb @@ -7,6 +7,7 @@ def setup @opt.def_option("-x [VAL]") {|x| @flag = x} @opt.def_option("--option [VAL]") {|x| @flag = x} @opt.def_option("-T [level]", /^[0-4]$/, Integer) {|x| @topt = x} + @opt.def_option("--enum [VAL]", [:Alpha, :Bravo, :Charlie]) {|x| @enum = x} @topt = nil @opt.def_option("-n") {} @opt.def_option("--regexp [REGEXP]", Regexp) {|x| @reopt = x} @@ -93,4 +94,9 @@ def test_lambda assert_equal(%w"", no_error {@opt.parse!(%w"--lambda")}) assert_equal(nil, @flag) end + + def test_enum + assert_equal([], no_error {@opt.parse!(%w"--enum=A")}) + assert_equal(:Alpha, @enum) + end end From c5ec052efc7e7dfc5f2e7c294cff3f12dfdbae6a Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Sun, 9 Mar 2025 22:39:12 +0900 Subject: [PATCH 2/2] Allow non-string enum list #79 Command line arguments are strings, convert enum list elements to strings to match. --- lib/optparse.rb | 2 +- test/optparse/test_placearg.rb | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/optparse.rb b/lib/optparse.rb index ade9870..11218fe 100644 --- a/lib/optparse.rb +++ b/lib/optparse.rb @@ -1503,7 +1503,7 @@ def make_switch(opts, block = nil) else raise ArgumentError, "argument pattern given twice" end - o.each {|pat, *v| pattern[pat] = v.fetch(0) {pat}} + o.each {|pat, *v| pattern[pat.to_s] = v.fetch(0) {pat}} when Module raise ArgumentError, "unsupported argument type: #{o}", ParseError.filter_backtrace(caller(4)) when *ArgumentStyle.keys diff --git a/test/optparse/test_placearg.rb b/test/optparse/test_placearg.rb index c6dc7ab..511541f 100644 --- a/test/optparse/test_placearg.rb +++ b/test/optparse/test_placearg.rb @@ -8,6 +8,7 @@ def setup @opt.def_option("--option [VAL]") {|x| @flag = x} @opt.def_option("-T [level]", /^[0-4]$/, Integer) {|x| @topt = x} @opt.def_option("--enum [VAL]", [:Alpha, :Bravo, :Charlie]) {|x| @enum = x} + @opt.def_option("--integer [VAL]", [1, 2, 3]) {|x| @integer = x} @topt = nil @opt.def_option("-n") {} @opt.def_option("--regexp [REGEXP]", Regexp) {|x| @reopt = x} @@ -99,4 +100,9 @@ def test_enum assert_equal([], no_error {@opt.parse!(%w"--enum=A")}) assert_equal(:Alpha, @enum) end + + def test_enum_conversion + assert_equal([], no_error {@opt.parse!(%w"--integer=1")}) + assert_equal(1, @integer) + end end