Help improving Daffy Duck Ruby lab


#1

print "Input here: "
user_input = gets.chomp
user_input.downcase!

if user_input.include? “s”
user_input.gsub!(/s/, “th”)
puts “Your input(1): #{user_input}”
elsif user_input == “”
print "Please input something: "
user_put = gets.chomp
user_put.gsub!(/s/, “th”)
user_put.downcase!
puts “Your input(2): #{user_put}”
else
print “There is no s present”
end

Link: https://www.codecademy.com/courses/learn-ruby/lessons/thith-meanth-war/exercises/congratulationth?action=resume_content_item

Here’s the code for one of the first Learn Ruby labs (Daffy Duck) I made where you make sentences replace the letter “s” with “th” . One of the ways they mentioned to improve code was “Think about how you might account for words in which the letter “c” sounds like an “s””. So I’m wondering how I could accomplish that?


#2

Also please give me any tips/ constructive criticism about how I wrote my code. Thanks!


#3

Using a bang! method comes with its own surprises. Never advisable if values are not first validated.

user_input = gets.chomp.downcase

at least stands a chance of never being nil.

One question, though… Why so many inputs?


#5

I was trying to improve code in the ways they asked. One way was creating if statement if user didn’t type in anything. How could I shorten the code if you think its too lengthy?


#6

In order to improve code, we first need to ensure that it at least works as expected. There is no need for two inputs, so that indicates something wrong, right there. What if the user enters nothing on the second go? Then what?

Clearly, we need a loop for the input but if you have not reached the unit on loops then we would be jumping ahead of ourselves. Try to get the code to work and for now just assume the user is inputting something, and not an empty string. If it is empty, though, it won’t matter. That means there is no s.

Follow the earlier suggestion for getting input that is not nil. Then swap the s's if there are any, else print that there is no s present. That’s the main gist of the program.

To improve it further, consider what you might by this time know about letter case so your program will recognize both lower and upper case s and replace it with the appropriate th or TH. Don’t step outside of the boundaries into areas that you have not yet studied. Work only with what you’ve been taught to this point.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.