読者です 読者をやめる 読者になる 読者になる

WORD TO DIGIT(CodeEval)

CHALLENGE DESCRIPTION:

Having a string representation of a set of numbers you need to print this numbers.

All numbers are separated by semicolon. There are up to 20 numbers in one line. The numbers are "zero" to "nine"

INPUT SAMPLE:

Your program should accept as its first argument a path to a filename. Each line in this file is one test case. E.g.

zero;two;five;seven;eight;four
three;seven;eight;nine;two

OUTPUT SAMPLE:

Print numbers in the following way:

025784
37892

My Code

#!/usr/bin/env ruby -w

def word_to_digit(word)
  case word
  when 'zero' then 0
  when 'one' then 1
  when 'two' then 2
  when 'three' then 3
  when 'four' then 4
  when 'five' then 5
  when 'six' then 6
  when 'seven' then 7
  when 'eight' then 8
  when 'nine' then 9
  end
end

ARGF.each_line do |line|
  puts line.chomp.split(';').map { |word|
    word_to_digit(word)
  }.join
end

By the way

There are so many challenges than I thought. It is too lazy to ready to a setup by every challenge, so I wrote a rake script.

require 'fileutils'

desc 'Create a codeeval skelton'
task :codeeval, 'challenge'
task :codeeval do |task, args|
  challenge = args.challenge
  if args.challenge.match(/\d+_(.+)/)
    script_name = $1
  else
    script_name = args.challenge
  end

  Dir.chdir Rake.original_dir
  FileUtils.mkdir_p challenge
  Dir.chdir challenge
  FileUtils.touch 'input.txt'
  template = <<-EOS
#!/usr/bin/env ruby -w

ARGF.each_line do |line|
  puts line.chomp
end
  EOS
  open("#{script_name}.rb", 'w') { |f| f.puts template }
  puts "created #{challenge}."
  puts "cd #{challenge}"
end

~/Rakefile に書くといろんなところから呼べるので良いのですが
~直下はドットファイルで管理したいなぁ。