January 2024
Intermediate to advanced
718 pages
20h 15m
English
Ruby has all the usual control structures, such as if statements and while loops. Java or JavaScript programmers may be surprised by the lack of braces around the bodies of these statements. Instead, Ruby uses the keyword end to signify the end of a body of a control structure:
| | today = Time.now |
| | |
| | if today.saturday? |
| | puts "Do chores around the house" |
| | elsif today.sunday? |
| | puts "Relax" |
| | else |
| | puts "Go to work" |
| | end |
Produces:
| | Go to work |
One thing you might find unusual is that in the second clause Ruby uses the keyword elsif—one word, missing an “e”—to indicate “else if”. Breaking that keyword up into else if would be a syntax error.
Similarly, while statements are terminated with
Read now
Unlock full access