- About Ruby
- Ruby Basics
- String, Printing and Symbols
- Ruby Arrays And Hashes
- Control Structures
- Functions
- Classes
- Modules
- And More
Example code based on
LearnXinYminutes
and licensed under
CC Attribution-Share 3
Modules
Collapse Content
Show Content
Modules
A Module is a collection of methods and constants. Module methods may be called without creating an encapsulating object
module ModuleExample
def foo
'foo'
end
end
# Including modules binds the methods to the object instance
# Extending modules binds the methods to the class instance
class Person
include ModuleExample
end
class Book
extend ModuleExample
end
Person.foo # => NoMethodError: undefined method `foo' for Person:Class
Person.new.foo # => 'foo'
Book.foo # => 'foo'
Book.new.foo # => NoMethodError: undefined method `foo'
Including Modules II
# Callbacks when including and extending a module are executed
module ConcernExample
def self.included(base)
base.extend(ClassMethods)
base.send(:include, InstanceMethods)
end
module ClassMethods
def bar
'bar'
end
end
module InstanceMethods
def qux
'qux'
end
end
end
class Something
include ConcernExample
end
Something.bar # => 'bar'
Something.qux # => NoMethodError: undefined method `qux'
Something.new.bar # => NoMethodError: undefined method `bar'
Something.new.qux # => 'qux'
Challenge
Ruby's Math module contain a large number of useful functions. Call Math's sqrt
function on the number 25.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
Florian
Mar 2, 1:29 PMFoo
nick
Mar 2, 4:43 PMbar
Ivan Chau
Mar 2, 10:10 PMUsing :: in first challenge should be correct.
Learneroo
Mar 2, 10:14 PM@Ivan, thanks, it's been added as possible answer.