0

I am currently just trying to wrap my head around this example question. I don't understand the syntax of it. I don't understand the point of i and how it relates to result

def pow(base, exponent)
  result = 1
  i = 1 
  while i <= exponent
    result = result * base
    i += 1
  end
  result 
end

Any explanation much appreciated!!

1 Answer 1

1

while need a do while(i <= exponent) do

i is a counter, you can replace the while for

exponent.times { result = result * base }

this code will execute the number (exponent) times the content of { }

And the result on end is the result of function, in ruby if you don't put a return clause will return the last line executed

Sign up to request clarification or add additional context in comments.

3 Comments

Actually while doesn't need a do.
@Jesper: it needs some way to tell it, where the condition ends and the loop body begins. There are two ways, either the keyword do or an expression separator (newline or ;). So, if you want to write it on one line and hate semicolons, then do is your only option. Adding it never hurts, but doing so when it is not required (as in this case) is un-idiomatic.
@JörgWMittag What made you think that I wasn't aware of that? I was simply refuting the clearly incorrect statement that a while needs a do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.