Re: Ruby Quiz - Challenge #7 - Type Inference - Convert Strings to Null, Number, Not a Number (NaN), Date & More


(Oleynikov) #1

It seems that my previous message wasn't delivered due to a couple of MIME
headers or for some other reason. At least I can't see it on either marc.info
or rubytalk.org. So I'm sending it again, sorry if you have received it twice.

Why not use regular expressions?

PATTERNS = {
  nan:   /\ANaN\z/,
  null:  /\An[iu]ll?\z/i,
  date:  /\A\d{4}\.\d{2}\.\d{2}\z/,
  float: /\A\d+\.\d+\z/,
  int:   /\A\d+\z/
}

def convert(values)
  values.map do |v|
    case v
    when PATTERNS[:nan]   then Float::NAN
    when PATTERNS[:null]  then nil
    when PATTERNS[:date]  then Date.strptime(v, '%Y.%m.%d')
    when PATTERNS[:float] then v.to_f
    when PATTERNS[:int]   then v.to_i
    else                       v.to_s
    end
  end
end

(Gerald Bauer) #2

Hello,

Why not use regular expressions?

  Good question.Welcome to the Ruby Quiz. Why not? Looks great. Passes
the test. Thanks for sharing your coding puzzle snippet / script. Keep
it up. Cheers. Prost.