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

[email protected]
Newsgroups gmane.comp.lang.ruby.general
Message-ID <[email protected]>
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
```


Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.