Re: Ruby Quiz - Challenge #7 - Type Inference - Convert Strings to Null, Number, Not a Number (NaN), Date & More
"Frank J. Cameron" <[email protected]>
| Newsgroups | gmane.comp.lang.ruby.general |
|---|---|
| Message-ID | <[email protected]> |
Gerald Bauer wrote:
> Challenge #7 - Type Inference - Convert Strings to Null, Number, Not a
> Number (NaN), Date & More
$ ruby lib/007.rb
Run options: --seed 42919
# Running:
.
Finished in 0.015037s, 66.5023 runs/s, 665.0233 assertions/s.
1 runs, 10 assertions, 0 failures, 0 errors, 0 skips
$ cat lib/007.rb
require_relative '../007/test.rb'
gem 'parslet', '~> 1.8.2'
require 'parslet'
class RubyQuizTest
@@parser = Class.new(Parslet::Parser) do
rule(:dte) {
(
match('[0-9]').repeat(4)>>(
match('[.]')>>match('[0-9]').repeat(2)
).repeat(2)
).as(:dte)
}
rule(:flt) {
(
match('[0-9]').repeat>>match('\.')>>match('[0-9]').repeat
).as(:flt)
}
rule(:int) {
match('[0-9]').repeat.as(:int)
}
rule(:nan) {
(
match('N')>>match('a')>>match('N')
).as(:nan)
}
rule(:nul) {
(
match('N')>>match('i')>>match('l') |
match('N')>>match('u')>>match('l')>>match('l')
).as(:nul)
}
rule(:str) {
match('.').repeat.as(:str)
}
rule(:foo) { nul | nan | dte | flt | int | str }
root(:foo)
end.new
@@transf = Class.new(Parslet::Transform) do
rule(:dte => simple(:dte)) { Date.strptime(dte, '%Y.%m.%d') }
rule(:flt => simple(:flt)) { flt.to_f }
rule(:int => simple(:int)) { int.to_i }
rule(:nan => simple(:nan)) { Float::NAN }
rule(:nul => simple(:nan)) { nil }
rule(:str => simple(:str)) { str.to_s }
end.new
def convert(values)
values.map{|v|
@@transf.apply(@@parser.parse(v))
}
end
end
RubyQuizTest.new('fjc')
Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>