Search code examples
rubymultiplicationexponentiation

Exponentiation not working


I'm new to programming, especially in Ruby so I've been making some basic projects. I have this code and as far as I know, it should work, but it gives results that I don't expect

The program takes a and B and returns a^b. I did this as a programming exercise, hence why I didn't just go a**b.

class Exponate
  attr_accessor :args

  def initialize args = {}
    @args = args
    @ans = nil
  end

  def index
    @args[:b].times {
      @ans = @args[:a] * @args[:a]
    }
    puts @ans
  end
end

e = Exponate.new(:a => 32, :b => 6)
e.index

e.args[:a] = 5
e.index

Returns

1024     # Should be 1_073_741_824
25       # Should be 15_625

But they are definitely not that


Solution

  • You can write like this:

    class Exponate
      attr_accessor :args, :ans
    
      def initialize args = {}
        @args = args
      end
    
      def index
        @ans = 1 # multiplication will start from 1
        @args[:b].times {
          @ans *=  @args[:a] #same as @ans = @ans * @args[:a]
        }
        puts @ans
      end
    end