Ich bin ein Anfänger Programmierer. Mein Code, der in Ruby ist, scannt grundsätzlich einen Text und findet heraus, wie oft ein bestimmtes Wort erscheint oder Wörter im Text ersetzt. Das erste, was ich nicht tun kann, ist, den Codeblock zu wiederholen. Wenn jemand will, ihren Text erneut zu scannen oder ersetzen müssen sie das Programm anstelle des Programms neu starten geht, habe ich versucht, dieses Problem zu lösen, indem Sie den gesamten Code-Block zu nehmen und Looping es, aber es hat nicht funktioniert und hat einen Fehler zurückgegeben . Die andere Sache ist, dass, wenn ich die Replace-Funktion verwende, es nur ein Wort ersetzt, im Gegensatz zu beiden. Zum Beispiel zeigt es Nahrung meme anstelle von Lebensmitteln Lebensmittel in das Bild unten: Wie kann ich diesen Codeblock wiederholen?
puts "insert your text: "
string = gets.chomp
puts "would you like to scan or replace your text?"
choice = gets.chomp
#this is the scan option which scans the text and outputs the amount of times a word is in it
if choice.include? "scan"
puts "what word would you like to scan?"
word_for_scan = gets.chomp
scan_count = string.scan(word_for_scan).count
puts "The word #{word_for_scan} appears #{scan_count} times"
#this is the replace function in the code which replaces the words in the text, as shown in the image above, whenever I try to replace something it only replaces one word instead of all of them
elsif choice.include? "replace"
puts "what word would you like to replace?"
word_for_replacement = gets.chomp
puts "what word would you like to replace it with?"
replacement_word = gets.chomp
replaced_text = string.sub(word_for_replacement, replacement_word)
puts "here is your new text: #{replaced_text}"
else
puts "error: would you like to scan or replace text?"
end
Vielen Dank für Blick auf den Code und versuchen, das Problem zu lösen.
Was bedeutet "es hat nicht funktioniert und gab einen Fehler zurück" bedeuten? * Wie genau * "hat es nicht funktioniert"? Was war die * genaue * Fehlermeldung? Bitte geben Sie eine [mcve] ein und probieren Sie Inputs und Outputs für Ihre gewünschten Ergebnisse aus, einschließlich aller Spezialfälle und Eckfälle. –