Over a million developers have joined DZone.

Determine If Syntactically Correct Characters Are Numeric Using Regex In Ruby

·
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")}"
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}