Forum: Ruby General Ruby syntax questions

Posted by Scott Price (drummerboi)
on 2013-01-25 04:16
-- 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
Posted by D. Deryl Downey (ddd)
on 2013-01-25 05:19
(Received via mailing list)
Err if you've used C++ even a little then 99% of that should make
perfect sense. What exactly don't you understand?


Scott Price wrote:
>    result = 1
> ------------------------------------
>    # return total
>        # divisor found; stop and return false!
> def primes(max)
>    end
>
>    # return primes_arr
>    primes_arr
> end
>

--
D. Deryl Downey

"The bug which you would fright me with I seek" - William Shakespeare -
The Winter's Tale, Act III, Scene II - A court of Justice.
Posted by Matthew Kerwin (mattyk)
on 2013-01-25 05:23
(Received via mailing list)
On 25 January 2013 13:16, Scott Price <lists@ruby-forum.com> 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#<=  <
http://www.ruby-doc.org/core-1.9.3/Fixnum.html#met...

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#+ 
<http://www.ruby-doc.org/core-1.9.3/Fixnum.html#method-i-2B
>

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 Kerwin, 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
Posted by Scott Price (drummerboi)
on 2013-01-25 05:57
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.
Posted by Matthew Kerwin (mattyk)
on 2013-01-25 06:16
(Received via mailing list)
On 25 January 2013 14:57, Scott Price <lists@ruby-forum.com> 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 Kerwin, 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
Posted by Carlo E. Prelz (Guest)
on 2013-01-25 07:10
(Received via mailing list)
Subject: Re: General Ruby syntax questions
  Date: Fri 25 Jan 13 02:15:09PM +0900

Quoting Matthew Kerwin (matthew@kerwin.net.au):

> 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
Posted by Matthew Kerwin (mattyk)
on 2013-01-25 07:15
(Received via mailing list)
On 25 January 2013 16:10, Carlo E. Prelz <fluido@fluido.as> 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 Kerwin, 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
Posted by unknown (Guest)
on 2013-01-25 08:01
(Received via mailing list)
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


Scott, you might also look into Integer#upto and Numeric#step.
Posted by Robert Klemme (robert_k78)
on 2013-01-25 08:40
(Received via mailing list)
On Fri, Jan 25, 2013 at 8:00 AM,  <sto.mar@web.de> 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. :-)

Cheers

robert
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.