rubynumbersrational-numbers

Pushing rational numbers


I have to make class NumberSet, which is a container for different kinds of numbers that can include only numbers that are not already in it.

class NumberSet
  include Enumerable

  def initialize
    @arr=[]
  end
  def each (&block)
    @arr.each do |member|
      block.call (member)
    end
  end
  def << number
    @arr<<number if @arr.include?(number) == false
  end
end

This code truncates the Rational numbers. For example, (22/7) should not equal (3/1).

mine=NumberSet.new
mine<<Rational(22/7)
# => [(3/1)]
mine<<3.0
# => nil

How can I fix this?


Solution

  • Your usage of Rational is wrong. Should be

    mine << Rational(22, 7)