Book class with title and pages attributesComparable module in the Book class<=> method to compare books by their pagesBook objects with exact titles and page counts< and == to compare the booksBook class with title and pages attributesComparable module in the Book class<=> method to compare books by their pagesBook objects with exact titles and page counts< and == to compare the booksBook with an initialize method that takes title and pages as parameters and sets them as instance variables.Use def initialize(title, pages) and set @title and @pages inside.
Book class, include the Comparable module and define the <=> method to compare Book objects by their pages attribute.Use include Comparable and define def <=>(other) to compare pages.
Book objects named book1 with title 'Ruby Basics' and pages 150, and book2 with title 'Advanced Ruby' and pages 200. Then, use book1 < book2 and book1 == book2 to compare them and store the results in variables is_shorter and is_equal respectively.Create book1 and book2 with exact titles and pages, then compare using < and ==.
is_shorter and is_equal exactly as shown: first print is_shorter, then print is_equal on the next line.Use puts is_shorter and puts is_equal to print the results.
What is the main purpose of including the Comparable module in a Ruby class?
<=> method and then gives the class comparison operators automatically.Which of the following is the correct way to define the comparison method <=> inside a Ruby class to use with Comparable?
class Box
include Comparable
def initialize(volume)
@volume = volume
end
def <=>(other)
?
end
endWhat will be the output of the following Ruby code?
class Person
include Comparable
attr_reader :age
def initialize(age)
@age = age
end
def <=>(other)
age <=> other.age
end
end
p1 = Person.new(30)
p2 = Person.new(25)
puts p1 > p2<=> method<=> method compares the ages of two Person objects using age <=> other.age.Identify the error in this Ruby class using Comparable and how to fix it:
class Item
include Comparable
def initialize(weight)
@weight = weight
end
def <=>(other)
@weight - other.weight
end
end<=>other.weight, but no weight method is defined in the class.attr_reader :weight allows other.weight to work correctly.You want to sort an array of Product objects by their price using Comparable. Which of the following is the best way to implement the <=> method?
class Product
include Comparable
attr_reader :price
def initialize(price)
@price = price
end
def <=>(other)
?
end
end<=> method contract<=> method should return -1, 0, or 1 depending on comparison.price <=> other.price correctly returns -1, 0, or 1. other.price <=> price reverses order, sorting descending. price - other.price returns a number but not guaranteed -1,0,1. price > other.price ? 1 : -1 returns only 1 or -1, missing 0 case.Pass the test and this pattern moves unknown