0
0
Rubyprogramming~20 mins

Self keyword behavior in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Self Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of self inside instance method
What is the output of this Ruby code?
Ruby
class Person
  def initialize(name)
    @name = name
  end

  def show_self
    puts self
  end
end

p = Person.new("Alice")
p.show_self
AAlice
B#<Person:0x00007fffe30b8c10>
CPerson
Dself
Attempts:
2 left
💡 Hint
Inside an instance method, self refers to the current object instance.
Predict Output
intermediate
2:00remaining
Output of self inside class method
What will this Ruby code print?
Ruby
class Car
  def self.show_self
    puts self
  end
end

Car.show_self
ACar
B#<Car:0x00007fffe30b8c10>
CObject
Dself
Attempts:
2 left
💡 Hint
Inside a class method, self refers to the class itself.
🔧 Debug
advanced
2:30remaining
Why does this code raise an error?
This Ruby code raises an error. What is the cause?
Ruby
class Animal
  def self.describe
    puts "This is an animal"
    puts self.name
  end

  def name
    "Generic Animal"
  end
end

Animal.describe
Aself.name calls a class method 'name' which is not defined, causing NoMethodError
BInstance method 'name' is called correctly, no error
CSyntax error due to missing 'end' keyword
Dself refers to an instance, but no instance exists
Attempts:
2 left
💡 Hint
Check if 'name' is defined as a class method or instance method.
🧠 Conceptual
advanced
2:00remaining
Meaning of self in module method
In Ruby, inside a module method defined with def self.method_name, what does self refer to?
AThe class that includes the module
BAn instance of the module
CThe module object itself
DThe main Object
Attempts:
2 left
💡 Hint
Modules are objects too in Ruby.
Predict Output
expert
3:00remaining
Output of self in nested context
What does this Ruby code print?
Ruby
class Outer
  def self.show
    puts self
    class Inner
      def self.show_inner
        puts self
      end
    end
    Inner.show_inner
  end
end

Outer.show
A
Outer::Inner
Outer
B
Outer
Inner
C
Outer
self
D
Outer
Outer::Inner
Attempts:
2 left
💡 Hint
Check what self refers to in each class method.