Objects Have Methods
Learn the need for defining methods of an object.
We'll cover the following
Methods
Methods are an object’s behavior.Objects have methods, allowing us to do interesting stuff with them. An object’s methods are things that the object can do.
Think about a person, like a friend. We can ask this person for their name (call a method), and they’ll tell us (return it to us). Their name is a piece of knowledge that this person has, and the ability to tell it to us (respond to our question) is a behavior (method) they have.
We could also ask them to bring us a cup of tea. Or, we could ask them to remember a phone number or email password.
As Rubyists, we say that we talk to objects or send messages to them. We do so by using (calling) methods they respond to.
What can objects do?
That depends on their class (type). Numbers can only do things that are useful for numbers. We can do the math and ask them about their mathematical properties, if they’re even or odd, for example. Strings (text) include far more methods, and they’re often related to text transformations.
Remember: Methods add useful behavior for particular types of objects.
We’ve already used some methods in the previous chapters. For example, "hello".upcase
calls the upcase
method on the "hello"
string.
Also, class
and is_a?
are methods defined on all objects in Ruby and are therefore also defined on the "a string"
string. The " a string".is_a?(String)
string answers with true
.