Following on from my learning I have also looked at classes and methods which is beginning to look very useful!
Methods
First great thing about method is that they are reusable procedures so it can easily remove any duplication. You can call them at any time and the availability of scope in a method is in a different scope.
We can add any getter or setter methods to change instance variables. A getter method gets a value of an instance variable. A setter method sets a value of an instance variable. We can use the accessors to automatically create the getter and setter methods without explicitly defining them. More information here
Define a method using def
and end
and will often provide it with arguments to use during the procedure. Any methods will return automatically the last line of the procedure even without the return
statement.
Scope availability
word = 'hello'
def say
puts word
end
say
# `say': undefined local variable or method `word' for main:Object (NameError)
The say method cannot access the variable word outside of its method as it only available locally to the method.
How do you access outside variable to use in the method?
Pass in the word variable as an argument
word = 'hello'
def say(a_word)
puts a_word
end
say(word)
# hello
Classes
A class is a blueprint where individual objects are created. When a new class is create an object of Class is initialised and assigned to a global constant ex. class Name
.
In a class we can store some attributes (e.g author of a book), store initial values and encapsulate state(attributes) to contain a state of a book. Encapsulation is used as a mechanism to restrict direct access to objects’ data and methods. It can be used to hide data members and members function. More here
class Book
end
book = Book.new
Creates a new instance of Book and automatically inherits the object methods
class Football
attr_reader :player, :team
def initialize(player, team)
@player = player
@team = team
end
def kick
puts "#{@player} from #{@team} kicks the ball!"
end
end
player1 = Football.new('Bianca', 'Makers')
player1.kick
attr_writer:
to be able to re-write them
attr_reader :player, :team
- Ruby will create a method for player and team under the hood like this:
def player
@player
end
The initialize method below runs automatically when a new instance of the class is created and assigns an instance variable.
def initialize(player, team)
@player = player
@team = team
end
Scope
When we use the class
keyword:
- The content of the class is embedded in an isolated scope so will not have access outside the class.
- You will need to pass in local variables if you wish to access them.
self
class Football
p self
end
# Football
self
now refers to the Hello class and not to the outside variable.