0
0
Rubyprogramming~20 mins

Class declaration syntax in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Class Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple Ruby class method call
What is the output of this Ruby code?
Ruby
class Greeter
  def greet
    "Hello, friend!"
  end
end

g = Greeter.new
puts g.greet
AError: undefined method
Bgreet
CGreeter
DHello, friend!
Attempts:
2 left
💡 Hint
Look at what the greet method returns and what puts does.
Predict Output
intermediate
2:00remaining
Output when accessing an instance variable
What will this Ruby code print?
Ruby
class Person
  def initialize(name)
    @name = name
  end

  def name
    @name
  end
end

p = Person.new("Alice")
puts p.name
AError: undefined variable
BPerson
CAlice
D@name
Attempts:
2 left
💡 Hint
The initialize method sets @name, and the name method returns it.
🔧 Debug
advanced
2:00remaining
Identify the error in this class declaration
What error does this Ruby code produce?
Ruby
class Animal
  def speak
    puts "Roar"
  end

  def speak
    puts "Meow"
  end
end

cat = Animal.new
cat.speak
AOutput: Meow
BNoMethodError: undefined method 'speak' for Animal
CRuntimeError: method redefinition error
DSyntaxError: unexpected end-of-input, expecting keyword_end
Attempts:
2 left
💡 Hint
Check if all methods and classes are properly closed with 'end'.
Predict Output
advanced
2:00remaining
Output of class variable usage
What is the output of this Ruby code?
Ruby
class Counter
  @@count = 0

  def initialize
    @@count += 1
  end

  def self.count
    @@count
  end
end

c1 = Counter.new
c2 = Counter.new
puts Counter.count
A2
B0
C1
DError: undefined class variable
Attempts:
2 left
💡 Hint
Class variables are shared among all instances.
🧠 Conceptual
expert
2:00remaining
Understanding inheritance and method overriding
Given these Ruby classes, what will be printed when calling d.speak?
Ruby
class Dog
  def speak
    "Woof"
  end
end

class LoudDog < Dog
  def speak
    super.upcase
  end
end

d = LoudDog.new
puts d.speak
AWoof
BWOOF
Csuper
DError: undefined method 'upcase' for nil
Attempts:
2 left
💡 Hint
The 'super' keyword calls the parent method, then upcase changes the string.