In CrystalLang, a method is a collection of statements that performs a specific task and returns a result. Methods are crucial for code organization and re usability, bundling one or more repeatable statements into a cohesive unit. Invoking a method in CrystalLang is done using dot notation. Key points about CrystalLang methods:
Definition: Methods are defined using the def keyword, followed by the method name and its parameters.
Functionality: They encapsulate a set of expressions that execute a particular operation.
Reusability: Methods enhance code modularity and reusability by allowing the same set of instructions to be executed multiple times.
Syntax: Method calls in CrystalLang involve invoking the method on an object using dot notation. Understanding methods is fundamental to effective CrystalLang programming, contributing to code clarity and maintainability.
class Sports
# Class method
def self.match_start
puts "match start"
end
# Instance method
def practice
puts "Practice hard"
end
end
Sports.match_start
s = Sports.new
s.practice
Output
match start
Practice hard
a class method can be called in conjunction with the name of the class, whereas the instance method requires you to create an instance to call the method.
why you need an instance method at all when it's so much easier to call a class method.
imagine that you have 3 methods in your class suppose you have to call a method 3 times, so there are two ways:- either call method via class or call method via instance variable lets take first
class Sports
# 3 methods inside
end
Sports.method_1
Sports.method_2
Sports.method_3
Calling the class every time doesn't look good and is considered to be bad programming practice. Essentially, this is creating 3 new objects in the program.
Creating an instance variable and calling all the methods with it is a better practice:
class Sports
# 3 methods inside
end
i = Sports.new
i.method_1
i.method_2
i.method_3
This way you're not creating a new instance of the class every time, instead you're using the same instance for all methods.
code is tested on :play.crystal-lang.org/#/cr