2016-03-31 9 views
-1

対象の行を元の6行とは反対の1行に減らすように求められました。なぜ私が間違いを起こしているのかの背後にある説明?Rubyスクリプトの繰り返しを減らそうとしています

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

どのようなエラーが表示されますか? – benbot

+0

ex16.rb:27:構文エラー、予期しないtIDENTIFIER、期待 ')' target.close) ^ ex16.rb:27:構文エラー、予期しない ')'、期待入力終了 target.close) ^ – chilledheat

+2

'target'はIOオブジェクトなので(sawaの特に熱心な編集の後では少し難しい)、もっと良い解決策は[IO#puts'](http://ruby-doc.org/core -2.3.0/IO.html#method-i-puts)。複数の引数をとり、 'target.puts(line1、line2、line3)'の後に自動的に改行を追加します。 –

答えて

1

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

を変更してみてください:

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は後続の改行を削除するためです。

+1

'' target.write $ stdin.gets'を使用してください。これは、 'gets'が' + "\ n" 'または' target.puts $ stdin 'で追加した末尾の\ n "'を持つためです。 'puts'は' '\ n" 'が既に存在する場合には' '\ n" 'を追加しないためです。 –

+1

No. [codereview.se]は、* working *コードの構造/デザイン/スタイル/パフォーマンスを改善するためのものです。 OPのコードは機能しません。それは解析さえしない。 –

2

文字列を書いているので、引用符で囲む必要があります。

あなたは以下を変更することができ

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

とてもシンプルです、ありがとう! – chilledheat

関連する問題