最大文字数の単語を抽出し、段階的に表示させる問題。
inject
を with_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:
- The word length is from 1 to 10 characters.
- The number of words in a line is from 5 to 15.
- If there are several words of the same length and they are the longest, then print the first word from the list.
- 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