Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jkarnowski/3e02f281bce7939f7951d3294f356e2c to your computer and use it in GitHub Desktop.
Save jkarnowski/3e02f281bce7939f7951d3294f356e2c to your computer and use it in GitHub Desktop.
# SELF
class Rat
def initialize
@age = 0
end
def self.run_away
p "pitter pitter patter"
end
def age!
@age += 1
end
end
rick = Rat.new
# how do you access #run_away? which one works? why?
# Rat.run_away versus rick.run_away
# how does a rat age? which one works? why?
# rick.age! versus Rat.age!
# USING MODULES AND CONSTANTS TOGETHER
# this allows you to use a CONSTANT in the method of a module
# if that class doesn't have that constant, things will break
module CoolActions
def say_the_thing
# one way:
eval("#{self.class}::SPEED")
# another way:
# self.class::SPEED
end
end
class Bats
SPEED = 123
include CoolActions
end
class Turtles
include CoolActions
end
test = Bats.new
# why does this work or not work?
test.say_the_thing
# what does this do?
test.methods
# P.S. eval - don't use it.
# http://stackoverflow.com/questions/1902744/when-is-eval-in-ruby-justified
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment