Module: Hashtostruct::StringToObject

Defined in:
lib/hashtostruct.rb

Instance Method Summary collapse

Instance Method Details

#to_objObject

Attempt to parse the string into a native Ruby object using standard formats

It currently looks for and converts:

  • integers

  • floats

  • exponents into floats

  • booleans

  • DateTimes in the formats:

    • yyyy-mm-dd

    • yyyy-mm-dd hh:mm:ss

    • hh:mm

    • hh:mm:ss

    • hh:mm:ssZ

    • hh:mm:ss.ss

    • hh:mm:ss(+-)hh:mm

    • hh:mm:ss(+-)hhmm

    • hh:mm:ss(+-)hh



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/hashtostruct.rb', line 30

def to_obj
  case self
  when /^(tru|fals)e$/
    self == 'true'
  when /^[+-]?\d+$/
    self.to_i
  when /^[+-]?\d+\.\d+$/ # floats
    self.to_f
  when /^[+-]?\d+(\.\d+)?[eE][+-]?\d+$/  # exponents
    self.to_f
  when /^(null|nil)$/
    nil
  when /^\d{2}:\d{2}(:\d{2}(\.\d+)?)?Z?$/
    DateTime.parse(self)
  when /^\d{2}:\d{2}:\d{2}[+-]\d{2}(:?\d{2})?$/
    DateTime.parse(self)
  when /^\d{4}-\d{2}-\d{2}$/
    DateTime.parse(self)
  when /^\d{4}-\d{2}-\d{2}[+-]\d{2}(:?\d{2})?$/
    DateTime.parse(self)
  when /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/
    DateTime.parse(self)
  else
    self
  end
end