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
Ahmad Abbas Zainol
Aug 26, 9:11 PMI have trouble to solve the last problem. How can I solve this?
Learneroo
Aug 26, 9:52 PMDid you do the previous challenges and make sure to implement the
to_s
method correctly for Product?Ahmad Abbas Zainol
Aug 26, 9:55 PMyes.. I already did... but still, I'm stuck and at Model class...
Learneroo
Aug 26, 10:05 PMHint: Make sure your Model's create method creates a new Product.
Ahmad Abbas Zainol
Aug 26, 10:10 PMI've already did that... but maybe there's something wrong with my code... still can't figure out the solution... I'm stuck at find method
Ahmad Abbas Zainol
Aug 26, 10:12 PMyes... finally.... I did manage to solve this problem... the problem with my code, instead writing, product = Product.new(name, description), I wrote product = Model.new(name, description).. thanks for the help...