summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLee Jarvis <leejarvis@fastmail.com>2020-01-17 08:51:06 +0000
committerGitHub <noreply@github.com>2020-01-17 08:51:06 +0000
commitc3825b39a56c1d64820ae30141c4604c857143b7 (patch)
tree86cb923b01d602ca410fc6dc1734a3aaf29a3dc8
parent02e3ec521f7a7440ec5d324e81e8ba85a749bcf0 (diff)
parente28fbcf19c9e1b6d8875be680c6bb4f40ab0c21c (diff)
downloadslop-c3825b39a56c1d64820ae30141c4604c857143b7.tar.gz
Merge pull request #250 from flavono123/float-scientific-notation
FloatOption: Add support for scientific notation and + sign
-rw-r--r--lib/slop/types.rb5
-rw-r--r--test/types_test.rb28
2 files changed, 30 insertions, 3 deletions
diff --git a/lib/slop/types.rb b/lib/slop/types.rb
index 4cd6136..c53319c 100644
--- a/lib/slop/types.rb
+++ b/lib/slop/types.rb
@@ -51,9 +51,10 @@ module Slop
# Cast the option argument to a Float.
class FloatOption < Option
+ FLOAT_STRING_REGEXP = /\A[+-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?\z/.freeze
+
def call(value)
- # TODO: scientific notation, etc.
- value =~ /\A-?\d*\.*\d+\z/ && value.to_f
+ value =~ FLOAT_STRING_REGEXP && value.to_f
end
end
diff --git a/test/types_test.rb b/test/types_test.rb
index ff1363c..d71c737 100644
--- a/test/types_test.rb
+++ b/test/types_test.rb
@@ -54,11 +54,37 @@ describe Slop::FloatOption do
@options = Slop::Options.new
@apr = @options.float "--apr"
@apr_value = 2.9
- @result = @options.parse %W(--apr #{@apr_value})
+ @minus = @options.float "--minus"
+ @plus = @options.float "--plus"
+ @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
assert_equal @apr_value, @result[:apr]
+ assert_equal (-6.1), @result[:minus]
+ 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