Concept Flow - Instance methods
Create Object
Call Instance Method
Method Uses Object's Data
Return or Print Result
End
An instance method is called on an object and can use that object's data to perform actions or return values.
class Dog def bark "Woof!" end end dog = Dog.new puts dog.bark
| Step | Action | Object State | Method Called | Output |
|---|---|---|---|---|
| 1 | Define class Dog with method bark | No objects yet | None | None |
| 2 | Create dog object with Dog.new | dog: instance of Dog | None | None |
| 3 | Call dog.bark | dog: instance of Dog | bark | "Woof!" |
| 4 | Print output of dog.bark | dog: instance of Dog | None | Woof! |
| 5 | End of program | dog: instance of Dog | None | None |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| dog | undefined | Dog instance created | Dog instance unchanged | Dog instance unchanged |
Instance methods belong to objects. Call them on an object, not the class. They can use the object's data. Syntax: def method_name inside class. Call: object.method_name Returns value or performs action.
What is an instance method in Ruby?
Which of the following is the correct way to define an instance method greet inside a Ruby class Person?
class Person ? end
def method_name inside the class without self..What will be the output of the following Ruby code?
class Dog
def bark
'Woof!'
end
end
fido = Dog.new
puts fido.barkFind the error in this Ruby code and select the fix that will make it work:
class Cat
def meow
puts 'Meow!'
end
end
kitty = Cat.new
kitty.meow()kitty.meow() is valid.Given the class below, what will puts user.full_name print?
class User
def initialize(first, last)
@first_name = first
@last_name = last
end
def full_name
"#{@first_name} #{@last_name}".upcase
end
end
user = User.new('Jane', 'Doe')upcase method.Pass the test and this pattern moves unknown