From 6995484ee3a4a505c1c8705709f8dc00899013b3 Mon Sep 17 00:00:00 2001 From: Hansuk Date: Thu, 16 Jan 2020 00:38:27 +0900 Subject: support scientific nations for float options - reference: https://stackoverflow.com/questions/638565/parsing-scientific-notation-sensibly - remove the todo comment(no idea for etc) Signed-off-by: Hansuk --- lib/slop/types.rb | 3 +-- test/types_test.rb | 20 +++++++++++++++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/lib/slop/types.rb b/lib/slop/types.rb index 07d7e62..c1055ea 100644 --- a/lib/slop/types.rb +++ b/lib/slop/types.rb @@ -52,8 +52,7 @@ module Slop # Cast the option argument to a Float. class FloatOption < Option def call(value) - # TODO: scientific notation, etc. - value =~ /\A[+-]?\d*\.*\d+\z/ && value.to_f + value =~ /\A[+-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?\z/ && value.to_f end end diff --git a/test/types_test.rb b/test/types_test.rb index 171c4d9..728b969 100644 --- a/test/types_test.rb +++ b/test/types_test.rb @@ -56,7 +56,9 @@ describe Slop::FloatOption do @apr_value = 2.9 @minus = @options.float "--minus" @plus = @options.float "--plus" - @result = @options.parse %W(--apr #{@apr_value} --minus -6.1 --plus +9.4) + @scientific_notation = @options.float "--scientific-notation" + @scientific_notation_value = 4e21 + @result = @options.parse %W(--apr #{@apr_value} --minus -6.1 --plus +9.4 --scientific-notation #{@scientific_notation_value}) end it "returns the value as a float" do @@ -65,6 +67,22 @@ describe Slop::FloatOption do assert_equal 9.4, @result[:plus] end + it "parses scientific notations" do + assert_equal @scientific_notation_value, @result[:scientific_notation] + @scientific_notation_value = 4E21 + @result = @options.parse %W(--scientific-notation #{@scientific_notation_value}) + assert_equal @scientific_notation_value, @result[:scientific_notation] + @scientific_notation_value = 4.0e21 + @result = @options.parse %W(--scientific-notation #{@scientific_notation_value}) + assert_equal @scientific_notation_value, @result[:scientific_notation] + @scientific_notation_value = -4e21 + @result = @options.parse %W(--scientific-notation #{@scientific_notation_value}) + assert_equal @scientific_notation_value, @result[:scientific_notation] + @scientific_notation_value = 4e-21 + @result = @options.parse %W(--scientific-notation #{@scientific_notation_value}) + assert_equal @scientific_notation_value, @result[:scientific_notation] + end + it "returns nil for non-numbers by default" do @result.parser.parse %w(--apr hello) assert_nil @result[:apr] -- cgit v1.2.1