0
0
Rubyprogramming~5 mins

Instance methods in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an instance method in Ruby?
An instance method is a function defined inside a class that can be called on objects (instances) created from that class. It operates on the data contained in the specific object.
Click to reveal answer
beginner
How do you define an instance method in a Ruby class?
You define an instance method inside a class using the <code>def</code> keyword followed by the method name. For example:<br><pre>class Dog
  def bark
    puts "Woof!"
  end
end</pre>
Click to reveal answer
beginner
How do you call an instance method in Ruby?
First, create an object (instance) of the class, then call the method on that object using dot notation. For example:<br>
dog = Dog.new
dog.bark  # Calls the bark method
Click to reveal answer
intermediate
What is the role of self inside an instance method?
Inside an instance method, self refers to the current object (instance) on which the method was called. It helps access or modify the object's data.
Click to reveal answer
intermediate
Can instance methods access instance variables? How?
Yes. Instance methods can read or change instance variables using the @ symbol. For example:<br>
def name
  @name
end
accesses the @name variable of the object.
Click to reveal answer
How do you define an instance method in Ruby?
AUsing <code>class method_name</code>
BUsing <code>def self.method_name</code> inside a class
CUsing <code>function method_name()</code>
DUsing <code>def method_name</code> inside a class
What does self refer to inside an instance method?
AThe current object (instance)
BA global variable
CThe class itself
DThe method name
How do you call an instance method named greet on an object person?
A<code>person.greet</code>
B<code>call greet on person</code>
C<code>Person.greet</code>
D<code>greet.person</code>
Can instance methods access instance variables?
ANo, only class methods can
BOnly if they are global variables
CYes, using the <code>@</code> symbol
DOnly if passed as arguments
Which of these is an instance method definition?
Adef self.run
Bdef run
Cdef Class.run
Ddef @run
Explain what an instance method is and how it is used in Ruby.
Think about how methods belong to objects.
You got /4 concepts.
    Describe how self works inside an instance method and why it is useful.
    Consider what 'self' means when you call a method on an object.
    You got /3 concepts.