On Fri, Jan 25, 2013 at 8:00 AM,  <[email protected]> wrote:
> Am 25.01.2013 05:23, schrieb Matthew Kerwin:
>
>> Note: a regular rubyist would probably just write:  `base ** exponent`
>
>
> Or (as an exercise) at least without using the while loop, e.g.
>
>
>   def pow(base, exponent)
>     result = 1
>     exponent.times { result = result * base }
>
>     result
>   end

We can make it a little shorter by using *=

def pow(base, exponent)
  result = 1
  exponent.times { result *= base }
  result
end

And while we're at it...

def pow(base, exponent)
  exponent.times.inject(1) {|result,| result * base}
end

All without error handling btw.  negative exponents wouldn't work so well. :-)

Cheers

robert


-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

-- 
[email protected] | 
https://groups.google.com/d/forum/ruby-talk-google?hl=en


Reply via email to