试图减少Ruby脚本中的重复

时间:2016-03-31 18:01:26

标签: ruby

我被要求将目标线减少到与原来的6条线相对的一条线。我为什么会收到错误的任何解释?

filename = ARGV.first

puts "We're going to create #{filename}"
puts "If you don't want that, hit CTRL-C (^C)."
puts "If you do want that hit RETURN (Enter)"

$stdin.gets

puts "Opening File..."
target = open(filename, 'w')

puts "Truncating the file."
target.truncate(0)

puts "Now I'm going to ask you for three lines."

print "line 1: + line 2: + Line 3:"
line1 = $stdin.gets.chomp
line2 = $stdin.gets.chomp
line3 = $stdin.gets.chomp

puts "I'm going to write these to the file."

target.write(#{line1}\n#{line2}\n#{line3})

puts "And finally, we close it."

target.close

2 个答案:

答案 0 :(得分:2)

由于您正在编写字符串,因此需要使用引号。

尝试更改

target.write(#{line1}\n#{line2}\n#{line3})

target.write("#{line1}\n#{line2}\n#{line3}")

答案 1 :(得分:1)

您可以更改以下内容:

line1 = $stdin.gets.chomp
line2 = $stdin.gets.chomp
line3 = $stdin.gets.chomp

target.write(#{line1}\n#{line2}\n#{line3})

成:

3.times { target.write $stdin.gets.chomp + "\n" }

或正如@thetinman指出的那样,简单地写$stdin.gets完成与$stdin.gets.chomp + "\n"相同的事情,因为所有chomp都会删除尾随换行符。

相关问题