後ろから数えてM番目の要素を出力。
設問
Write a program to determine the Mth to last element of a list.
Input sample:
The first argument will be a text file containing a series of space delimited characters followed by an integer representing a index into the list(1 based), one per line. e.g.
a b c d 4 e f g h 2
Output sample:
Print to stdout, the Mth element from the end of the list, one per line. If the index is larger than the list size, ignore that input.
e.g.
a g
やってみた
#!/usr/bin/env ruby ARGF.lines do |line| elm = line.split(/\s/).instance_eval{ |x| x[0..-2][-x.last.to_i] } puts elm if elm end
配列の「最後の要素」と「それ以外」を分ける方法が見つからず
最近覚えたinstance_evalで処理。
こちらを見てみるときれいに分割していた。
こんな風に書けるんだね。
RubyでMth to last elementを解く-CodeEval - hp12c
*alpha, ns = line.split(/\s/)