Bird
0
0

Find the bug in this Ruby code using functional style inside an OOP class:

medium📝 Debug Q7 of 15
Ruby - Functional Patterns in Ruby
Find the bug in this Ruby code using functional style inside an OOP class:
class Multiplier
  def initialize(factor)
    @factor = factor
  end

  def multiply(numbers)
    numbers.map { |n| n * factor }
  end
end

m = Multiplier.new(3)
puts m.multiply([1, 2, 3]).inspect
Amap method cannot be used on arrays.
Bfactor should be @factor inside the block.
Cmultiply method should return a string.
Dinitialize method is missing a return statement.
Step-by-Step Solution
Solution:
  1. Step 1: Identify variable usage inside block

    Inside the block, 'factor' is undefined; instance variable @factor should be used.
  2. Step 2: Understand Ruby instance variable scope

    Instance variables require @ prefix to be accessed inside blocks or methods.
  3. Final Answer:

    factor should be @factor inside the block. -> Option B
  4. Quick Check:

    Use @factor to access instance variable inside blocks [OK]
Quick Trick: Use @ for instance variables inside blocks [OK]
Common Mistakes:
  • Using local variable names instead of instance variables
  • Thinking map cannot be called on arrays
  • Expecting initialize to return a value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes