0

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?

sawa
  • 165,429
  • 45
  • 277
  • 381
user103220
  • 35
  • 1
  • 9

2 Answers2

4

Your usage of Rational is wrong. Should be

mine << Rational(22, 7)
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
1

With the newest Ruby, you should do:

mine << 22/7r
sawa
  • 165,429
  • 45
  • 277
  • 381