Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)
Refactoring
"Phenomenal cosmic powers, itty bitty living space." -Genie: Aladdin
Ruby is often referred to as a programmer's best friend because it strives to make the programmer's life easier. What is a programming language at its core? It's a language that both humans and machines can understand. When you think of it that way, you can focus on improving comprehension for both parties involved.
The process of simplification is what programmers refer to as refactoring. This optimization saves programmers time without diminishing the programs functionality.
Take for instance this if/else statement.
age = 24
if age == 21
puts "You're Blue team."
elsif age == 22
puts "Green team's over there."
elsif age == 23
puts "You belong in Orange."
elsif age == 24
puts "To the Red team with you!"
else
puts "This is for 21 to 24 year olds."
end
⇩
To the Red team with you!
When and Then
Let's condense the if/else statement into a case statement that allows us to use when and then.
age = 22
case age
when 21 then puts "You're Blue team."
when 22 then puts "Green team's over there."
when 23 then puts "You belong in Orange"
when 24 then puts "To the Red team with you!"
else puts "This is for 21 to 24 year olds."
end
⇩
Green team's over there.
As you can see this is much easier to understand. Some would say it's eloquent. We can even minimize our if statements. After your case statement add this line:
puts "Come back next year though." if age == 20
Change your age to 20 and run the file.
⇩
This is for 21 to 24 year olds.
Come back next year though.
Ternary Conditional Expression
We can condense the if/else statement further by creating ternary conditional expressions. We call it ternary because it takes three arguments.
print true ? "Yes, that is true." : "No, that is not true."
⇩
Yes, that is true.
The question mark checks to see if the prior boolean or statement is true. If it's true the first string is printed. If it's false the second string is printed. Just like an else/if.
print 5 < 3 ? "You know it." : "Of course it's not."
⇩
Of course it's not.
Conditional Assignment
There are times when we only want to set a variable to a certain value when that variable doesn't already have a value. However, if the variable already has a value, we'd rather not mess with it.
candy = nil #nil means nothing
candy ||= "Gummy Bear"
candy ||= "Candy Bar"
puts candy
⇩
Gummy Bear
The variable candy is being set to the string "Gummy Bear" because it doesn't have an existing value. Then on the next line we tell candy to be "Candy Bar" if candy doesn't already have a value. Because candy has the value of "Gummy Bear" we don't change the variables value. We could change the variable value by removing the pipes.
candy = nil
candy ||= "Gummy Bear"
candy = "Candy Bar"
puts candy
⇩
candy Bar