Wednesday, May 22, 2013

Ruby Lesson 2 Section 4 of 4 and Project: Review and Thith Meanth War!

I am going to take this time to reflect that these lessons are the foundations of Ruby. As such it is important to know 100% of what is being taught, not 99%. This is because any small holes in our knowledge now can easily destroy a program later on. Remember, it only takes one bad line of code to crash a program.


The importance of Lesson 2 is that it will let us initiate / escape blocks of code later on. More on that in Lesson 3. 

Now on to the project! 

Thith Meanth War! 


From now on I will be displaying the finished code and then break down each new concept / function. Codeacademy also does this and it is helpful to know what the finished product should look like, what it does, and to review if you get things wrong. The downside of this is that people will have the tendency to cheat (copy straight from the finished product), or maybe it's just me lol. 

This program will replace all "s"s with "th". The goal is to make anything you print sound like Daffy Duck. 

CODE:

print "Thtring, pleathe!: "
user_input = gets.chomp
user_input.downcase!

if user_input.include? "s"
  user_input.gsub!(/s/, "th")
else
  puts "Nothing to do here!"
end
  
puts "Your string is: #{user_input}"

* Note that in a previous lesson I stated that writing a code like "user_input = gets.chomp.downcase!" will result in the same result as writing the way it's shown above. This is no longer the case in this program. Writing it all in one line will cause no substitution to take place. This is a reminder to always becareful where you place methods and of the ! function as it might have unintended consequences. 

Now, most of this string should look familiar except for the ".include?" and ".gsub!(/s/, "the")

.include? tells Ruby to see if the letter "s" is present in the user_input. If there is it runs the code .gsub!. This will then substute the any letter inside the "/ /" and replace them with what exists inside the quotations after the comma. 

It is important to know that ".gsub!(/ /, " ")" must be written exactly as is with no spaces between .gsub! and the "(" sign. If there is a space there will be an error. 

No comments:

Post a Comment