Determine whether a string contains an Integer or a Float in Ruby -
let's input string, , know whether contains integer
or float
.
for example:
input_1 = "100" input_2 = "100.0123"
now, let's take account following:
input_1.respond_to?(:to_f) # => true input_1.is_a?(float) # => false input_1.is_a?(fixnum) # => false input_1.to_f? # => 100.0 input_2.respond_to?(:to_i) # => true input_2.is_a?(integer) # => false input_2.is_a?(fixnum) # => false input_2.to_i # => 100
in cases above, can't determine whether string contains integer
or float
. there way in ruby determine whether string contains fixnum
or float
?
you use regular expressions:
n = '100.0' if n =~ /\a\d+\z/ puts 'integer' elsif n =~ /\a\d+\.\d+\z/ puts 'float' else puts 'not integer or float' end
edit regular expressions taste.
Comments
Post a Comment