Newbie question:
I know how include and extend work, what I am wondering is if there is a way to get both class and instance methods from a single module?
This is how I do it with two modules:
module InstanceMethods
def mod1
"mod1"
end
end
module ClassMethods
def mod2
"mod2"
end
end
class Testing
include InstanceMethods
extend ClassMethods
end
t = Testing.new
puts t.mod1
puts Testing::mod2
Thanks for taking your time ...
A class method is a method that's shared among all objects. To call a class method, put the class as the first argument. Class methods can be can be called from instances and from the class itself.
"method" is a function that is a attached to an object or class. A module is a group of defined functions, classes, consrants, etc.
The method definitions look similar, too: Module methods are defined just like class methods. As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.
Yes. It's exactly as simple as you would expect, due to the genius of ruby:
module Methods
def mod
"mod"
end
end
class Testing
include Methods # will add mod as an instance method
extend Methods # will add mod as a class method
end
t = Testing.new
puts t.mod
puts Testing::mod
Or, you could do:
module Methods
def mod1
"mod1"
end
def mod2
"mod2"
end
end
class Testing
include Methods # will add both mod1 and mod2 as instance methods
extend Methods # will add both mod1 and mod2 as class methods
end
t = Testing.new
puts t.mod1
puts Testing::mod2
# But then you'd also get
puts t.mod2
puts Testing::mod1
module Foo
def self.included(m)
def m.show1
p "hi"
end
end
def show2
p "hello"
end
end
class Bar
include Foo
end
Bar.new.show2 #=> "hello"
Bar.show1 #=> "hi"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With