Methods and instance variables
Right now, we can’t do much with a person aside from create it with a name. Its age will always be zero. So lets add a method that makes a person become older:
def initialize(@name : String)
@age = 0
end
def age
@age
end
def become_older
@age += 1
end
end
peter = Person.new "Peter"
john.age # => 0
john.age # => 1
peter.age # => 0
Method names begin with a lowercase letter and, as a convention, only use lowercase letters, underscores and numbers.
For more information on getter and setter macros, see the standard library documentation for Object#getter, , and Object#property.
As a side note, we can define become_older
inside the original Person
definition, or in a separate definition: Crystal combines all definitions into a single class. The following works just fine:
class Person
def initialize(@name : String)
@age = 0
end
end
class Person
def become_older
@age += 1
end
You can invoke the previously redefined method with previous_def
:
class Person
@age += 1
end
end
class Person
def become_older
previous_def
@age += 2
end
end
person = Person.new "John"
person.become_older
person.age # => 3
Without arguments or parentheses, previous_def
receives all of the method’s parameters as arguments. Otherwise, it receives the arguments you pass to it.
This will initialize @age
to zero in every constructor. This is useful to avoid duplication, but also to avoid the Nil
type when reopening a class and adding instance variables to it.