如何确定字符串中的数字类型?

Aru*_*gin 1 ruby validation numeric

我们有这些字符串:

  • "1/2"
  • "1"
  • "0.9"
  • "B"
  • "0,9"

如何确定字符串的数据类型?

  • 有理数
  • 整数
  • 浮动
  • 不是数字
  • 不是数字

在一段代码?

fen*_*ngd 6

{Rational => :to_r, Integer => :to_i, Float => :to_f }.each do |key, sym|
  ["1/2", "1", "0.9"].each do |item|
    puts "#{item} is #{key}" if item.send(sym).to_s == item
  end
end

#1/2 is a Rational
#1 is a Integer
#0.9 is a Float
Run Code Online (Sandbox Code Playgroud)

对于"非数字"的情况,我认为这很容易提升一点