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

Stepwise Word(CODEEVAL)

最大文字数の単語を抽出し、段階的に表示させる問題。
injectwith_index と組み合わせて利用できるというのを知れたのが収穫。
 

CHALLENGE DESCRIPTION:

Print the longest word in a stepwise manner.

INPUT SAMPLE:

The first argument is a path to a file. Each line contains a test case with a list of words that have different or the same length.

cat dog hello
stop football play
music is my life

OUTPUT SAMPLE:

Find the longest word in each line and print it in one line in a stepwise manner. Separate each new step with a space. If there are several words of the same length and they are the longest, then print the first word from the list.

h *e **l ***l ****o
f *o **o ***t ****b *****a ******l *******l
m *u **s ***i ****c

CONSTRAINTS:

  1. The word length is from 1 to 10 characters.
  2. The number of words in a line is from 5 to 15.
  3. If there are several words of the same length and they are the longest, then print the first word from the list.
  4. The number of test cases is 40.

My Code

#!/usr/bin/env ruby -w

def stepwise(word)
  word.each_char.with_index.inject([]) do |result, (char, i)|
    mask = "#{'*' * i}"
    result << "#{mask}#{char}"
  end
end

ARGF.each_line do |line|
  words = line.chomp.split
  max_length_word = words.max_by(&:size)
  puts stepwise(max_length_word).join(" ")
end