Create a gist now

Instantly share code, notes, and snippets.

Any of these should be runnable at the command line by `ruby <filename>`
module SayHello
def hello
puts "hello from SayHello"
end
end
include SayHello
hello
include Math
puts sqrt(25)
module Herp
def herp
"herp"
end
end
class Derp
include Herp
end
puts Derp.new.herp
# you can use extend to add new class methods
module Home
def steal
"home"
end
end
class Score
extend Home
end
puts Score.steal
# what's going on with extend
module Inspector
def saywhat
self.inspect
end
end
class Derp
include Inspector
extend Inspector
end
puts Derp.new.saywhat
puts Derp.saywhat
module M
CONSTANT = "value"
end
class C
include M
end
class D
extend M
end
puts C::CONSTANT
puts D::CONSTANT # wha?
# gotcha fix
class Module
def extend_with_constants(mod)
extend mod
mod.constants.each do |constant|
const_set(constant, mod.const_get(constant))
end
end
end
module M
CONSTANT = "value"
end
class C
extend_with_constants M
end
puts C::CONSTANT
module M
end
module N_the_game_master
end
class C
include M
include N_the_game_master
end
puts C.included_modules.inspect
module M
def hello
"Hi there!"
end
end
class C
end
class D
end
class E
end
C.class_exec do
include M
end
D.module_exec do #alias
include M
end
E.send(:include, M)
puts C.new.hello
puts D.new.hello
puts E.new.hello
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment