< Back to Ruby notes

Operators

Controlling the Flow of Logic

Resources:


If, Else, While

unless @read_only
  @title = new_title
end

# This is the same as...

@title = new_title unless @read_only
@title = new_title if @writable        # You can use other logic statements too

If you need a simple “if, else” statement for something, use the ternary operator like so:

greeting = name ? "Hello #{name}" : "What's your name?"

Case Statements

Case statements are good for more complex code reliant on, or assigning, a range of different values. These lines can also be collap

case attack
when 'punch'
    puts 'Not the face!'
when 'kick' puts then 'My leg!' # Same as above, works since code is simple
else
    puts 'Ha, you missed!'
end

response = case attack
           when 'punch' then 'Not the face!'
           when 'kick' then 'My leg!'
           else 'Ha, you missed!'
           end
  @name ||= 'Default name!'