查找包含10个以上字符且小于20的输入行

时间:2014-02-03 02:51:16

标签: ruby

我有以下要求的代码

输入:键盘上的文本行列表。

输出:每个输入行都有> 10个字符但是< 20个字符(不包括新行),包含字符串"ed"

我需要修改此代码:

while(a=gets.chomp)
  puts a if a.length>10 and a.length<20 and a.include?'ed'
  break if a.length.zero?
end

在写完所有输入行后打印所有行,这意味着首先我需要使用键盘编写所有行,然后在完成后,它将只显示符合要求的行。

1 个答案:

答案 0 :(得分:1)

input = [] # prepare container for good lines
while(a=gets.chomp)
  break if a.empty?
  input << a if a.length.between?(11..19) and a.include?('ed')
end
puts input.join "\n" # print them out

只是出于好奇,如果 Ctrl + D 可以作为输入终结符:

puts "Use Ctrl+D to process"
puts $stdin.readlines.select {|l|
  l.length.between?(11..19) and l.include?('ed')
}

或者,甚至:

puts $stdin.each_line.inject([]) do |m,l|
  l.chomp!
  break m if l.empty?  
  m << l if l.length.between?(11..19) and l.include?('ed')
end