0
0
Rubyprogramming~20 mins

Instance methods in Ruby - Practice Problems & Coding Challenges

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

  def greet
    "Hello, #{@name}!"
  end
end

person = Person.new("Alice")
puts person.greet
AHello, Alice!
BHello, @name!
Cperson.greet
DError: undefined method greet
Attempts:
2 left
💡 Hint
Instance methods can access instance variables using @variable_name.
Predict Output
intermediate
2:00remaining
Instance method modifying state
What will be the output after running this Ruby code?
Ruby
class Counter
  def initialize
    @count = 0
  end

  def increment
    @count += 1
  end

  def current
    @count
  end
end

counter = Counter.new
counter.increment
counter.increment
puts counter.current
A2
B0
C1
DError: undefined method current
Attempts:
2 left
💡 Hint
Each call to increment adds 1 to @count.
🔧 Debug
advanced
2:00remaining
Why does this instance method raise an error?
This Ruby code raises an error when calling display. What is the cause?
Ruby
class Book
  def initialize(title)
    title = title
  end

  def display
    puts "Title: #{title}"
  end
end

book = Book.new("Ruby Guide")
book.display
AMissing return statement in initialize method
BSyntax error in initialize method
CUndefined local variable or method `title` in display method
DCannot call puts inside instance method
Attempts:
2 left
💡 Hint
Instance variables start with @ and are needed to keep data between methods.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in this instance method
Which option correctly identifies the syntax error in this Ruby code?
Ruby
class Calculator
  def add(a, b)
    return a + b
  end

  def multiply(a, b)
    a * b
  # missing end here
end

calc = Calculator.new
puts calc.add(2, 3)
AMissing parentheses in method call add(2, 3)
BMissing <code>end</code> keyword for multiply method
CIncorrect use of return in add method
DCannot create instance of Calculator without arguments
Attempts:
2 left
💡 Hint
Every method definition must be closed with end.
🚀 Application
expert
3:00remaining
How many times is the instance method called?
Consider this Ruby code. How many times is the log instance method called during execution?
Ruby
class Logger
  def initialize
    @count = 0
  end

  def log(message)
    @count += 1
    puts "Log ##{@count}: #{message}"
  end

  def repeat_log(times, message)
    times.times { log(message) }
  end
end

logger = Logger.new
logger.log("Start")
logger.repeat_log(3, "Repeat")
logger.log("End")
A6
B4
C3
D5
Attempts:
2 left
💡 Hint
Count each explicit call to log, including inside loops.