0
0
Rubyprogramming~20 mins

Why operators are methods in Ruby - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Operator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Ruby code using operator methods?

In Ruby, operators like + are actually methods. What will this code print?

Ruby
class Number
  attr_reader :value
  def initialize(value)
    @value = value
  end

  def +(other)
    Number.new(@value + other.value + 1)
  end

  def to_s
    @value.to_s
  end
end

n1 = Number.new(2)
n2 = Number.new(3)
puts (n1 + n2).to_s
A6
B5
C7
DError: undefined method '+' for Number
Attempts:
2 left
💡 Hint

Remember the + method adds the two values and then adds 1 extra.

🧠 Conceptual
intermediate
1:30remaining
Why are operators methods in Ruby?

Why does Ruby treat operators like + and - as methods?

ABecause Ruby does not support functions
BBecause Ruby only supports procedural programming
CBecause operators are faster as methods
DBecause it allows operator overloading and custom behavior for objects
Attempts:
2 left
💡 Hint

Think about how you can change how + works for your own classes.

🔧 Debug
advanced
2:00remaining
What error does this Ruby code raise?

What error will this code produce?

Ruby
class Box
  def +(other)
    @size + other.size
  end
end

b1 = Box.new
b2 = nil
puts b1 + b2
ATypeError: nil can't be coerced into Integer
BNoMethodError: undefined method 'size' for nil:NilClass
CNoMethodError: undefined method '+' for Box
DSyntaxError: unexpected end-of-input
Attempts:
2 left
💡 Hint

Check if @size is initialized before use.

📝 Syntax
advanced
1:30remaining
Which option correctly defines the * operator method in Ruby?

Choose the correct way to define the * operator method that multiplies two objects' values.

A
def *other
  @value * other.value
end
B
def * (other)
  @value * other.value
end
C
def *(other)
  @value * other.value
end
D
def multiply(other)
  @value * other.value
end
Attempts:
2 left
💡 Hint

Remember the operator method name is the operator symbol itself.

🚀 Application
expert
2:30remaining
What is the output of this Ruby code using operator methods and inheritance?

Consider this Ruby code. What will it print?

Ruby
class Animal
  def +(other)
    "Animal plus Animal"
  end
end

class Dog < Animal
  def +(other)
    super + " and Dog plus Dog"
  end
end

d1 = Dog.new
d2 = Dog.new
puts d1 + d2
AAnimal plus Animal and Dog plus Dog
BDog plus Dog
CAnimal plus Animal
DNoMethodError: undefined method '+' for Dog
Attempts:
2 left
💡 Hint

Look at how super is used inside the + method in Dog.