Conditions and loops
Ruby has the usual if and loops, plus a few extras that make code read like sentences: unless, modifiers at the end of a line, and a very flexible case. In practice, you'll loop over collections with methods like each far more often than with while.
if, elsif, else
No parentheses around conditions, no braces: blocks close with end. Note the spelling: elsif, not elseif or else if.
Modifiers and unless
A one-line condition can go after the statement. unless means "if not":
Use unless only for simple conditions. unless a && !b is hard to read, so use if then.
Comparison and logic
<=> (the "spaceship operator") returns -1, 0 or 1, and is what sorting uses. == compares values (1 == 1.0 is true); eql? also checks the type.
case / when
case compares one value against many patterns. Each when can be a value, a list, a range, a class or a regular expression:
There's no fall-through (no break needed), and case returns a value too.
Pattern matching
case / in (pattern matching) checks the shape of data and pulls values out of it in one step. It's great for parsed JSON and API responses:
name: on its own captures the value into a variable called name. [*, "admin", *] means "an array containing "admin" anywhere".
Loops
Iterating with methods (the Ruby way)
%w[apple banana cherry] is a shortcut for ["apple", "banana", "cherry"]. The { |i| … } and do |i| … end parts are blocks, which you'll study properly in Blocks, procs and iterators.
while, until and loop
| Keyword | Does |
|---|---|
next |
Skip to the next iteration (like continue elsewhere) |
break |
Leave the loop (can return a value: break result) |
redo |
Repeat this iteration (rare) |
There's also a for x in list loop, but Ruby programmers almost always use each instead.
Finding things without a loop
Many loops you'd write in other languages are single methods in Ruby:
FizzBuzz, the Ruby way
A case with no value works like a chain of if/elsif.
Practice
- Ask for an age with
getsand printchild,teenoradultusingcasewith ranges. - Print a multiplication table for 7 with
1.upto(10). - Use
loopandbreakto keep asking for a number until the user types0(put several lines in the Input box). - Use pattern matching to print the city from
{ user: { address: { city: "Pune" } } }.
1.How do you write "else if" in Ruby?
2.What does puts "Sold out" if stock.zero? do?
3.Which keyword skips to the next iteration of a loop?
4.In case x when 1..9, what does the range do?