Skip to content

Instantly share code, notes, and snippets.

@nizaroni
Last active November 15, 2016 11:04
Show Gist options
  • Save nizaroni/a72272bb8879684a0657 to your computer and use it in GitHub Desktop.
Save nizaroni/a72272bb8879684a0657 to your computer and use it in GitHub Desktop.
Ruby cheatsheet.

Ruby Cheatsheet

Classes and Instances

Creating a class

A class is a blueprint.

class Spaceship
end

Creating an instance of a class

An instance is something you build from the blueprint.

my_ship = Spaceship.new

Adding a method to your class

A method is an action you perform with your instance.

class Spaceship

  def fly
    # do things
  end

end

The initialize method

Called automatically when you make an instance with .new.

Use it primarily to set up initial values for variables.

class Spaceship

  def initialize(name, speed)
    @name = name
    @speed = speed
    @crew = []
  end

end

Attribute accessors

class Spaceship

  attr_accessor(:name, :speed)

  def initialize(name, speed)
    @name = name
    @speed = speed
    @crew = []
  end
end

Arrays

.push

Adds an item to an array.

my_numbers = [ 1, 2, 3, 4, 5, 6 ]

my_numbers.push(7)
my_numbers.push(8, 9, 10)

.each

Loops over an array.

my_numbers = [ 1, 2, 3, 4, 5, 6 ]

my_numbers.each do |number|
  # my_numbers contains integers so number is an integer
  puts number * 2
end

.map

Loops over an array to produce a new array.

my_numbers = [ 1, 2, 3, 4, 5, 6 ]

times_ten = my_numbers.map do |number|
  number * 10
end

puts times_ten
#=> [ 10, 20, 30, 40, 50, 60 ]

.reduce

Loops over an array to produce a single value.

my_numbers = [ 1, 2, 3, 4, 5, 6 ]

final = my_numbers.reduce(0) do |sum, number|
  sum + number
end

puts final
#=> 1 + 2 + 3 + 4 + 5 + 6  =  21

Fixing Common Errors

Check mispelling of variables

enterprise = Spaceship.new

# should be enterprise with lowercase e
Enterprise.fly

Check mispelling of methods

Especially initialize.

class Spaceship
  # VERY tough to catch this typo of initialize
  def intialize
    # do things
  end
end

Don't forget your accessors

class Spaceship
  # Missing attr_accessor for name

  def initialize(@name, @speed)
    @name = name
    @speed = speed
  end
end

falcon = Spaceship.new("Milennium Falcon", 400)

# No accessor for name!
puts falcon.name

Don't forget to end

class, def, do, if..else all need end.

class Spaceship
  def initialize(name, speed)
  @name = name
  @speed = speed
end
# MISSING end

It helps a lot to find missing end keywords when you...

Indent your code

If the former example was properly indented, it would be easy to catch the missing end.

class Spaceship
  def initialize(name, speed)
    @name = name
    @speed = speed
  end

# MISSING end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment