0
0
Rubyprogramming~10 mins

Comparable module usage in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to include the Comparable module in the class.

Ruby
class Box
  include [1]
end
Drag options to blanks, or click blank then click option'
AComparable
BEnumerable
CKernel
DMath
Attempts:
3 left
💡 Hint
Common Mistakes
Including Enumerable instead of Comparable
Forgetting to include any module
Including unrelated modules like Math
2fill in blank
medium

Complete the code to define the <=> method for comparing boxes by volume.

Ruby
class Box
  include Comparable

  def initialize(length, width, height)
    @length = length
    @width = width
    @height = height
  end

  def volume
    @length * @width * @height
  end

  def [1](other)
    volume <=> other.volume
  end
end
Drag options to blanks, or click blank then click option'
Aequals
Bcompare_to
C<=>
Dcompare
Attempts:
3 left
💡 Hint
Common Mistakes
Using method names like compare or equals instead of <=>
Not defining the <=> method at all
3fill in blank
hard

Fix the error in the comparison method name to enable Comparable functionality.

Ruby
class Box
  include Comparable

  def initialize(size)
    @size = size
  end

  def [1](other)
    @size <=> other.size
  end

  protected

  attr_reader :size
end
Drag options to blanks, or click blank then click option'
Acompare
Bequals
Ccompare_to
D<=>
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect method names like compare or equals
Misspelling the <=> operator
4fill in blank
hard

Fill both blanks to create a hash mapping box volumes to their sizes, filtering volumes greater than 100.

Ruby
boxes = [Box.new(2, 3, 4), Box.new(5, 5, 5), Box.new(1, 1, 1)]
volume_map = {box.[1] => box.[2] for box in boxes if box.volume > 100}
Drag options to blanks, or click blank then click option'
Avolume
Bsize
Cheight
Dlength
Attempts:
3 left
💡 Hint
Common Mistakes
Using attributes that don't exist or are unrelated
Mixing up keys and values
5fill in blank
hard

Fill all three blanks to create a hash of box sizes to volumes, including only boxes with volume less than 50.

Ruby
boxes = [Box.new(1, 2, 3), Box.new(2, 2, 2), Box.new(3, 3, 3)]
result = {box.[1] => box.[2] for box in boxes if box.volume [3] 50}
Drag options to blanks, or click blank then click option'
Asize
Bvolume
C<
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong comparison operators
Swapping keys and values