ruby - 查找字符串中的内容类型(数字、日期、时间、字符串等)

标签 ruby string parsing types

我正在尝试解析一个 CSV 文件并使用 SQL 命令自动为其创建一个表。 CSV 中的第一行给出了列标题。但我需要推断每个列的类型。

Ruby 中是否有任何函数可以找到每个字段中内容的类型。 例如,CSV 行:

"12012", "Test", "1233.22", "12:21:22", "10/10/2009"

应该产生像这样的类型

['integer', 'string', 'float', 'time', 'date']

谢谢!

最佳答案

require 'time'

def to_something(str)
  if (num = Integer(str) rescue Float(str) rescue nil)
    num
  elsif (tm = Time.parse(str)) == Time.now
    # Time.parse does not raise an error for invalid input
    str
  else 
    tm
  end
end

%w{12012 1233.22 12:21:22 10/10/2009 Test}.each do |str|
  something = to_something(str)
  p [str, something, something.class]
end

结果在

["12012", 12012, Fixnum]
["1233.22", 1233.22, Float]
["12:21:22", Sat Sep 12 12:21:22 -0400 2009, Time]
["10/10/2009", Sat Oct 10 00:00:00 -0400 2009, Time]
["Test", "Test", String]

ruby 1.9.3 更新:stdlib 中的 Time 类现在会在无法解析字符串时抛出异常,因此:

def to_something(str)
  duck = (Integer(str) rescue Float(str) rescue Time.parse(str) rescue nil)
  duck.nil? ? str : duck
end

关于ruby - 查找字符串中的内容类型(数字、日期、时间、字符串等),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1415819/

相关文章:

ruby - 如何找到所有匹配所有部分的正则表达式?

c++ - 我被字符串和数组困住了

c++ - double to std::string with dynamic precisicion (without trailing zeros)

ruby-on-rails - Rails 与 namespace 的多态关联

ruby - 阻止 Ruby 自动转义字符串

具有数组属性的 Ruby 类

java - 从字符串中删除前 3 个字符

c# - 有没有一种直接的方法来检索浏览器呈现但未在实际 html 文件中硬编码的文本?

JavaScript 身份验证 JSONString : [object Object], [object 对象]

linux - 一般颜色列表