简体   繁体   中英

Printing a redacted word from an if loop in RUBY

I am going through the exercises in codecademy and am stuck at a place where my code isn't doing what I need it to do. All I need it to do is print the words but if the word is redacted, I need it to print "REDACTED". From what I can see, that is what my code is doing but I must have a symbol in the wrong place or something is missing. So, if anyone can see where I went wrong, I sure would appreciate a nudge in the right direction! Thanks you kindly! Here's my code :

puts "Whats your input brah?"
text = gets.chomp
puts "Whatchu are you hiding bro?"
redact = gets.chomp
words = text.split(" ")
words.each {|x| if x == redact print "REDACTED"+" " else print x+" "}

words is an array, and redact is a string. So you can't compare them using == . What you're trying to do is see if redact is present anywhere in words . You can do this using include? :

if words.include?(redact) ...

An even better way to implement this would be to use a regex on the original input string:

print text.gsub(/\b#{redact}\b/, 'REDACTED')

I found the answer. Thank you all anyway!

puts "Whats your input brah?"
text = gets.chomp
puts "Whatchu are you hiding bro?"
redact = gets.chomp
words = text.split(" ")
words.each {|x| if x == redact then print "REDACTED"+" " else print "#{x}"+" " end}

Use $end instead of end for

words.each 
{
 |x| 
 if x == redact 
   print "REDACTED"+" " 
 else 
   print x+" "
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM