Class Methods and Modules


Premium Content - Free Preview

Class methods

class methods are called on the overall class instead of a specific Object. They are created with the self keyword (to refer to the class itself):

class Dog     
  def self.greet(message)
    "Woof #{message} woof!"
  end    
end

Without creating any specific dogs, you can use Dog's greet method:

Dog.greet("hello") #=> Woof hello woof!

All classes come with a class method called .new. This is how new instances of a class are created:

doggy = Dog.new #=> # (new Dog instance)

Class methods cannot be called on instances; Ruby will raise an error if you try it:

doggy.greet("hello") 
#=> NoMethodError: undefined method `greet' for #<Dog:0x001016>

Note that class Dog should be used to create Dog instances. If you just want to groups multiple 'class' methods together, use a module instead.

Modules

Modules in Ruby are used to bundle groups of methods (and constants) together under one name so they can be easily re-used.

For example, Ruby's Math module provides many useful math methods:

 Math.sqrt(81)  #=> 9.0
 Math.hypot(3,4)  #=> 5.0 

Math.sqrt returns the square root of a number.
Math.hypot returns the hypotenuse of a right-angled triangle with those sides.


End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Comments

Contact Us
Sign in or email us at [email protected]