makersacademy / ruby-kickstart

Ruby Kickstart
MIT License
39 stars 382 forks source link

Exercise 2:12 - janky behaviour on `lowest` method #306

Closed emmett-walsh closed 8 years ago

emmett-walsh commented 8 years ago

Ok gang, my turn please.

My lowest method is behaving oddly. When i call it separately to the initialize method in two steps it behaves as expected:

f = Fraction.new(20,60)
f.lowest
f.numerator # => 1
f.denominator # => 3

When the methods are concatenated it seems to reverse the numerator and denominator values for some arcane reason:

f = Fraction.new(20,60).lowest
f.numerator # => 3
f.denominator # => 1

Any sage advice would be greatly appreciated. Full code for the exercise is as follows:

class Fraction
  attr_accessor 'numerator', 'denominator'

  def initialize(numerator, denominator)
    @numerator = numerator
    @denominator = denominator
  end

  def gcd(a,b)
    return a if b == 0
    gcd(b, a%b)
  end

  def lowest
    lowest = gcd(@numerator, @denominator)
    @numerator /= lowest
    @denominator /= lowest
  end

  def to_f
    @numerator.to_f / @denominator.to_f
  end

  def to_s
    "#{@numerator}/#{@denominator}"
  end

end
emmett-walsh commented 8 years ago

Just saw nmrichards had same issue, already solved. whoops!