Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
In this stage, we're going to learn how to call methods on an object. To be clear, we're not talking about passing an argument to a method. We mean taking a piece of data and calling a method that is only available on that piece of data.
When we talk about calling methods on an object, we mean taking a piece of data and calling a method that is only available on that piece of data. For example, strings have one set of methods available on them. And numbers have a different set of methods.
"a string".length
"another string".upcase
"a third string".reverse
7.even?
-12.abs
5.next
When you call a method, it's important for Ruby to know which object you're calling it on, because the behavior of the method will vary based on the object. We type the dot operator following an object to indicate that we're calling a method on it.
puts "AA".length # 2
puts "AAAAAAAAA".length # 9
puts 3.odd? # true
puts 4.odd? # false
puts 3.even? # false
puts 4.even? # true
Or, in place of the object itself, we can use a variable that refers to that object:
string = "AA"
puts string.length # 2
number = 4
puts number.even? # true
Chaining methods
- You want to know if a string contains an even number of characters.
- Call
length
on the string - Call
even?
on number returned fromlength
- Could store length in a variable, then call
even?
on the value in the variable - Instead, can "chain" the method calls by putting a dot operator and a method name directly following the previous method call
- Should only do this in situations where you're sure the first method call won't fail. Otherwise, subsequent methods will error. But you'll often see this done in Ruby code, so it's good to be aware of it.
- Call
puts "AAA".length.even? # false
puts "AA".length.even? # true
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up