General Ruby syntax questions

– Can sombody please break these down and let me know what each line of
these examples are doing. I’ve used c++ a little, but I’m new to Ruby.
Any response would be greatly appreciated.

def pow(base, exponent)
result = 1

i = 1
while i <= exponent
result = result * base
i += 1
end

result
end


def sum(nums)
total = 0

i = 0
while i < nums.count
total += nums[i]

i += 1

end

return total

total
end


def is_prime?(num)
i = 2
while i < num
is_divisible = ((num % i) == 0)

if is_divisible
  # divisor found; stop and return false!
  return false
end

i += 1

end

no divisors found

true
end

def primes(max)
primes_arr = []

i = 2
while i < max
if is_prime?(i)
# i is prime; add it to the array
primes_arr << i
end

i += 1

end

return primes_arr

primes_arr
end

Err if you’ve used C++ even a little then 99% of that should make
perfect sense. What exactly don’t you understand?

Scott P. wrote:

result = 1

return total

   # divisor found; stop and return false!

def primes(max)
end

return primes_arr

primes_arr
end


D. Deryl D.

“The bug which you would fright me with I seek” - William Shakespeare -
The Winter’s Tale, Act III, Scene II - A court of Justice.

Thanks Matthew. I have one single question about the first section of
code. I know it returns the base raised to the exponent, but what does
the variable “i” stand for? I probably sound stupid asking these things,
but I have basically no experience coding. I just played with c++ for a
little while. I was never good.

On 25 January 2013 13:16, Scott P. [email protected] wrote:

– Can sombody please break these down and let me know what each line of
these examples are doing. I’ve used c++ a little, but I’m new to Ruby.
Any response would be greatly appreciated.

First, a question: where did you find this code? It’s not what we could
consider “typical Ruby,” in fact it looks a lot like what a C/C++
programmer would write. As such, seeing as you’ve “used C++ a little,”
surely you could work out what is going on?

Anyway, I’ll break down a function or two the way I understand the
interpreter to work (note: not necessarily how any of them actually
work)
in case it’s helpful.

def pow(base, exponent)

Define a method called ‘pow’.
It has two named parameters, called ‘base’ and ‘exponent’.
Given the context I can’t say for sure on which object this method is
defined, but for the sake of tutorial, for now let’s just say it’s a
“global” function.

result = 1

Create a variable called ‘result’, and assign to it the value 1. Under
the
hood I’d interpret that as: make the ‘result’ variable refer to the
singleton Fixnum object ‘1’

i = 1

Ditto, but called ‘i’

while i <= exponent

Invoke the method ‘<=’ on the object referred to by variable ‘i’, with
its
parameter being the object referred to by variable ‘exponent’.
See: Fixnum#<= <
Class: Fixnum (Ruby 1.9.3)>

Use the result (return value) of that method as the condition in a
‘while’
expression.

result = result * base

Invoke the method '’ on the object referred to by variable ‘result’,
with
its parameter being the object referred to by variable ‘base’.
See: Fixnum#

<http://www.ruby-doc.org/core-1.9.3/Fixnum.html#method-i-2A

Assign the result of that method to the ‘result’ variable. (i.e. update
the ‘result’ variable to point to the object returned from #* )

i += 1

Syntactic sugar for: i = i + 1

Invoke the method ‘+’ on the object referred to by variable ‘i’, with
its
parameter being the single Fixnum object ‘1’.
See: Fixnum#+
<Class: Fixnum (Ruby 1.9.3)

Assign the result of that method to the ‘i’ variable. (I.e. update the
‘i’
variable to point to the object returned from #+ )

end

Marks the end of the current scope/block/whatever you want to call it.
In this case implies an execution jump back to the ‘while’ statement
three
lines above.

result

end

These two lines go hand-in-hand. The former is a simple statement which
evaluates to the value of the ‘result’ variable.
‘end’ again marks the end of the current scope/block/etc., in this case
the
chunk of code that started with ‘def’. I.e. it indicates the end of the
function.
Since the value of a chunk of code is always the value of the last
expression evaluated in it, and the last expression in this function was
the ‘result’ bit, the return value of this function is the final value
of
the ‘result’ variable.

Note: a regular rubyist would probably just write: base ** exponent

Actually, I won’t write out the others, because I don’t have time.
Hopefully this has been illuminating in some way. And if I’ve gotten
anything wrong, someone please correct me.

Cheers

Matthew K., B.Sc (CompSci) (Hons)
http://matthew.kerwin.net.au/
ABN: 59-013-727-651

“You’ll never find a programming language that frees
you from the burden of clarifying your ideas.” - xkcd

On 25 January 2013 14:57, Scott P. [email protected] wrote:

Thanks Matthew. I have one single question about the first section of
code. I know it returns the base raised to the exponent, but what does
the variable “i” stand for? I probably sound stupid asking these things,
but I have basically no experience coding. I just played with c++ for a
little while. I was never good.

By convention, in most programming contexts, ‘i’ is often to count
iterations of a loop.

for (i = 0; i < number_of_iterations; i++)

… is pretty ubiquitous. In a nested loop, usually the inner loop uses
‘j’, and then ‘k’, etc.


Matthew K., B.Sc (CompSci) (Hons)
http://matthew.kerwin.net.au/
ABN: 59-013-727-651

“You’ll never find a programming language that frees
you from the burden of clarifying your ideas.” - xkcd

Subject: Re: General Ruby syntax questions
Date: Fri 25 Jan 13 02:15:09PM +0900

Quoting Matthew K. ([email protected]):

By convention, in most programming contexts, ‘i’ is often to count
iterations of a loop.

for (i = 0; i < number_of_iterations; i++)

… is pretty ubiquitous. In a nested loop, usually the inner loop uses
‘j’, and then ‘k’, etc.

Comes from Fortran, where, unless otherwise specified, variables whose
names begun with the letters I to M were implicitly typed as
integers. Thus, loop indices were most commonly I, J, K, L and M.

Carlo

On 25 January 2013 16:10, Carlo E. Prelz [email protected] wrote:

… is pretty ubiquitous. In a nested loop, usually the inner loop uses
‘j’, and then ‘k’, etc.

Comes from Fortran, where, unless otherwise specified, variables whose
names begun with the letters I to M were implicitly typed as
integers. Thus, loop indices were most commonly I, J, K, L and M.

I did not know that. Cool, thanks Carlo.


Matthew K., B.Sc (CompSci) (Hons)
http://matthew.kerwin.net.au/
ABN: 59-013-727-651

“You’ll never find a programming language that frees
you from the burden of clarifying your ideas.” - xkcd

Am 25.01.2013 05:23, schrieb Matthew K.:

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

Scott, you might also look into Integer#upto and Numeric#step.

On Fri, Jan 25, 2013 at 8:00 AM, [email protected] wrote:

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. :slight_smile:

Cheers

robert