Calling Methods on an Object5:13 with Jay McGavren
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 third string".reverse
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
- You want to know if a string contains an even number of characters.
lengthon the string
even?on number returned from
- 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.
puts "AAA".length.even? # false
puts "AA".length.even? # true
You need to sign up for Treehouse in order to download course files.Sign up