2016-03-31 12 views
-1

Hedef hattımı orijinal 6 hattımın aksine bir satıra indirmem istendi. Neden hata aldığımı anlatan bir açıklama var mı? Eğer bir dize yazıyoruz yanaRuby komut dosyasında tekrarlamayı azaltmaya çalışmak

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

Ne tür bir hata alıyorsunuz? – benbot

+0

ex16.rb: 27: sözdizimi hatası, beklenmedik tIDENTIFIER, bekliyor ')' target.close) ^ ex16.rb: 27: sözdizimi hatası, beklenmedik ')', bekliyor sonu girişi target.close) ^ – chilledheat

+2

'Hedef' bir IO nesnesi olduğundan (sawa'nın özellikle hevesli düzenlemesinden sonra söylemek biraz zor), ['IO # puts'] kullanmak daha iyi bir çözüm olabilir (http://ruby-doc.org/core -2.3.0/IO.html # yöntem-i-koyar), birden çok argüman alır ve her biri sonra bir satırsonu otomatik olarak ekler: "target.puts (satır1, satır2, satır3)". –

cevap

1

aşağıdaki:

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

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

içine:

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

veya @thetinman'ın işaret ettiği gibi, sadece $stdin.gets yazıyor $stdin.gets.chomp + "\n" ile aynı şeyi başarır, çünkü tüm chomp sondaki yeni satırı kaldırır.

+1

Ya da 'target.write $ stdin.gets' işlevini kullanın, çünkü' '' '' '' '' '' n '' n '' 'n' ', hatta' 'target.puts $ stdin' 'ile ekliyorsunuzdur. "koyar", zaten var ise "\ n" 'bir satır eklemez. –

+1

Hayır. [Codereview.se] * çalışma * kodunun yapısını/tasarımını/stilini/performansını iyileştirmek içindir. OP'nin kodu çalışmıyor. Ayrılmıyor bile. –

2

, bu tırnak içinde olması gerekiyor.

deneyin değişen

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

için
target.write("#{line1}\n#{line2}\n#{line3}") 
değiştirebilirsiniz
+0

çok basit, çok teşekkürler! – chilledheat

İlgili konular