< Back to Ruby notes

Eloquent Ruby

Writing ruby the right way

Resources:


1) Write Code that Looks Like Ruby

2) Choose the Right Control Structure

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

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
end

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
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!'

3) Take Advantage of Ruby’s Smart Collections