DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Fred has posted 10 posts at DZone. View Full User Profile

Determine If Syntactically Correct Characters Are Numeric Using Regex In Ruby

08.07.2010
| 428 views |
  • submit to reddit
        Determine if syntactically correct characters are numeric using regex.
An extension to this function would handle float 
exponents and associated characters.
http://www.ruby-forum.com/topic/88507

#!/usr/bin/ruby -w

def is_numeric?(s)
  return (s.to_s =~ /^\d+(\.\d+|\d*)$/)?true:false
end

puts "is_numeric?(1.2345) #=> #{is_numeric?(1.2345)}"
puts "is_numeric?(12345678987654321) #=> #{is_numeric?(12345678987654321)}"
puts "is_numeric?(0) #=> #{is_numeric?(0)}"
puts "is_numeric?(0.0) #=> #{is_numeric?(0.0)}"
# puts "is_numeric?(.001) #=> #{is_numeric?(.001)}" # results in compile error
puts "is_numeric?(\".001\") #=> #{is_numeric?(".001")}"
puts "is_numeric?(\"0.001\") #=> #{is_numeric?("0.001")}"
puts "is_numeric?(123435.12345) #=> #{is_numeric?(123435.12345)}"
puts "is_numeric?(\"123435.\") #=> #{is_numeric?("123435.")}"
puts "is_numeric?(\"a\") #=> #{is_numeric?("a")}"