
Saved by Harold T. Harper
The Well-Grounded Rubyist
Saved by Harold T. Harper
You tell by knowing the rule in C: a dangling else goes with the last unmatched if (the first of the two behaviors in this example). But in Ruby, you have end to help you out: if x > 50 if x > 100 puts "Big number" else puts "Medium number" end end
A third way to express a negative condition is with unless. The unless keyword The unless keyword provides a more natural-sounding way to express the same semantics as if not or if !: unless x == 1
It’s not uncommon to see a conditional modifier at the end of a statement in a case like this one: puts "Big number!" if x > 100 This is the same as if x > 100 puts "Big number!" end You can also do this with unless: puts "Big number!" unless x <= 100
Conditional modifiers have a conversational tone. There’s no end to worry about. You can’t do as much with them (no else or elsif branching, for example), but when you need a simple conditional, they’re often a good fit.
The single else in this statement has to belong to the second if, because that if hasn’t yet hit its end. The first if and the last end always belong together, the second if and the second-to-last end always belong together, and so forth. The if/end pairs encircle what belongs to them, including else. Of course, this means you have to place your en
... See moreConditional execution often involves more than one branch; you may want to do one thing if the condition succeeds and another if it doesn’t. For example, if the password is correct, let the user in; otherwise, print an error message. Ruby makes full provisions for multiple conditional branches, using else and elsif.
Sometimes you want an if condition to be negative: if something isn’t true, then execute a given segment of code. You can do this in several ways. Negating conditions with not and ! One way to negate a condition is to use the not keyword: if not (x == 1) You can also use the negating ! (exclamation point, or bang) operator: if !(x == 1)
Public is the default access level; if you don’t specify that a method is protected or private, it’s public. Public instance methods are the common currency of Ruby programming. Most of the messages you send to objects are calling public methods.
The workhorse of conditional execution, not surprisingly, is the if keyword. if clauses can take several forms. The simplest is the following: if condition # code here, executed if condition is true end The code inside the conditional can be any length and can include nested conditional blocks. You can also put an entire if clause on a single line,
... See moreIf you don’t use an explicit receiver for a method call, Ruby assumes that you want to send the message to the current object, self. Thinking logically, you can conclude that the message add_egg has an object to go to only if self is an object that responds to add_egg. In other words, you can only call the add_egg instance method of Baker when self
... See more