0
0
Rubyprogramming~20 mins

Self keyword behavior in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding the Self Keyword in Ruby
📖 Scenario: Imagine you are creating a simple Ruby class to represent a person. You want to understand how the self keyword works inside instance methods and class methods.
🎯 Goal: Build a Ruby class called Person that uses the self keyword to show how it refers to the current object inside instance methods and to the class itself inside class methods.
📋 What You'll Learn
Create a class called Person with an instance variable @name.
Add an instance method called show_self_instance that returns self.
Add a class method called show_self_class that returns self.
Create an instance of Person with the name "Alice".
Call both methods and print their results.
💡 Why This Matters
🌍 Real World
Understanding <code>self</code> helps you write clear Ruby classes that behave correctly when methods are called on objects or the class itself.
💼 Career
Many Ruby jobs require knowledge of object-oriented programming and how <code>self</code> works to build maintainable and bug-free code.
Progress0 / 4 steps
1
Create the Person class with an initialize method
Create a class called Person with an initialize method that takes a parameter name and sets it to an instance variable @name.
Ruby
Need a hint?

Use class Person to start the class and def initialize(name) to define the constructor.

2
Add an instance method that returns self
Inside the Person class, add an instance method called show_self_instance that returns self.
Ruby
Need a hint?

Define a method with def show_self_instance and return self.

3
Add a class method that returns self
Add a class method called show_self_class inside the Person class that returns self. Use the self. prefix to define the class method.
Ruby
Need a hint?

Define a class method with def self.show_self_class and return self.

4
Create an instance and print results of both methods
Create a variable called person and set it to a new Person instance with the name "Alice". Then print the result of calling person.show_self_instance and Person.show_self_class.
Ruby
Need a hint?

Use person = Person.new("Alice") to create the instance. Use puts to print the method results.