< Back to Ruby notes

Eloquent Ruby

Writing ruby the right way


1) Write Code that Looks Like Ruby

2) Choose the Right Control Structure

unless @read_only
  @title = new_title

# 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?"

Use each instead of for, since for basically calls the each method itself, creating an avoidable inefficiency.

list = ["item one", "item two", "item three"]

list.each do |item|
    puts item

Case statements are also 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
    puts 'Ha, you missed!'

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

3) Take Advantage of Ruby’s Smart Collections