forked from rubyworks/facets
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request rubyworks#78 from u2/master
Add String#number? method.
- Loading branch information
Showing
3 changed files
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
class String | ||
|
||
# Returns true if it's a decimal digits. | ||
# | ||
# "123_456_789_123_456_789.123_456_000_111".number? # => true | ||
# "1.23".number? # => true | ||
# "1.23a".number? # => false | ||
# | ||
# CREDIT: u2 | ||
|
||
def number? | ||
!!self.match(/\A[+-]?\d+?(_?\d+?)*?(\.\d+(_?\d+?)*?)?\Z/) | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
covers 'facets/string/number' | ||
|
||
test_case String do | ||
|
||
method :number? do | ||
|
||
test do | ||
x = "1.23\n" | ||
x.number?.assert == true | ||
end | ||
|
||
test do | ||
x = "123_456_789_123_456_789.123_456_000_111\n" | ||
x.number?.assert == true | ||
end | ||
|
||
test do | ||
x = ".123\n" | ||
x.number?.assert == false | ||
end | ||
|
||
test do | ||
x = "123_\n" | ||
x.number?.assert == false | ||
end | ||
|
||
test do | ||
x = "_123\n" | ||
x.number?.assert == false | ||
end | ||
|
||
test do | ||
x = "23_456_789_123_456_.245\n" | ||
x.number?.assert == false | ||
end | ||
|
||
test do | ||
x = "23_456_789_123_456._245\n" | ||
x.number?.assert == false | ||
end | ||
|
||
end | ||
|
||
end |