Skip to content

Commit

Permalink
Merge pull request rubyworks#78 from u2/master
Browse files Browse the repository at this point in the history
Add String#number? method.
  • Loading branch information
trans committed Jan 31, 2014
2 parents 30574f7 + c85846b commit 0992de6
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/core/facets/string.rb
Expand Up @@ -31,6 +31,7 @@
require_relative 'string/natcmp.rb'
require_relative 'string/nchar.rb'
require_relative 'string/newlines.rb'
require_relative 'string/number.rb'
require_relative 'string/op_div.rb'
require_relative 'string/op_sub.rb' # included in `remove`.
require_relative 'string/outdent.rb'
Expand Down
14 changes: 14 additions & 0 deletions lib/core/facets/string/number.rb
@@ -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
44 changes: 44 additions & 0 deletions test/core/string/test_number.rb
@@ -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

0 comments on commit 0992de6

Please sign in to comment.