Flow Control Flashcards
If Else
if else in ruby works as an expression so you can assign it to a variable
EX
message = if lander_cnt > 10 then "Launching" else "Waiting" end
EX:
Short statements on one line
launch if can_launch?
falsy
only things that are falsy are nil and literal false
“unless” single statement version
EX
launch unless feul_level < 25
Ternary operator
EX
can_launch? ? launch : wait
Conditional initialization
&&=
I don’t remember what this is for
||=
Is far more common and people often use this to initialize a variable if it hasn’t already been initialized.
EX
ship ||= Spaceship.new
Case statement
EX
car_status = case feul_level when "low" then "bad" when "medium" then "fine" when "high" then "great" else "not sure, good luck!"
While loop
long EX
while high_alert? sound_system.play_siren_cycleend
short EX
while high_alert? do sound_system.play_siren_cycle end
shortest EX
sound_system.play_siren_cycle while high_alert?
Until loop
inverts the while condition
EX
until ship.at_crusing_velocity? ship.accelerateend
Shortest EX
ship.accelerate until ship.at_cruising_velocity?
begin end block
Caveat: This code will execute at least once even if your condition is false from the start.
EX
begin lightning.start_flashing sound_system.play_siren_cycleend while hight_alert?begin ship.accelerate make_fake_engine_noiseend until ship.at_cruising_velocity
For loop
nobody uses it.
loop (without block)
EX
loop do go_another_light_year puts "this is not the edge of the universe"end
upto() & downto() methods
EX
20.downto(10) {|i| puts i}
or
10.upto(20) { |i| puts i}
.times method
EX
3.times {puts "This is serenity, please respond"}
step
- Iterates over the range, passing each nth element to the block.
- If begin and end are numeric, n is added for each iteration.
- Otherwise, step invokes succ to iterate through range elements.
- If no block is given, an enumerator is returned instead.
EX1
.step(10,2) { |i| puts i}
next
next starts the next iteration