Login Register






A beginners guide to Ruby, Part 3 filter_list
Author
Message
A beginners guide to Ruby, Part 3 #1
Nightc||ed's Beginner Ruby Guide


if/else and case classes:

In every language, there's some type of if/else statement. Even in batch.
if/else statements in Ruby are structured like so:
Code:
if <variable> = <condition> <do this> elsif <variable> = <some other condition> #not needed but usually used. Can have as many as you want <do this> else #if the variable is anything else <do this> end #ends the statement
As mentioned, you can have as many elsif statements as you want, but they get a little confusing after a while. That's why I prefer case classes for more complex conditionals.
The case class is structured similar to if/else but a little more abstract.
Code:
case <variable> when <condition> <do this> when <other condition> <do this> end
Again, you can have as many whens as you'd like and you MUST use end to finish your class.

Math:

Math in Ruby is pretty simple, but extremely useful.
the operators are as follows:
Code:
+ #addition - #subtraction * #multiplication / #division % #modulus (divides and returns remainder) ** #exponent
There are also some special methods for advanced math:
Code:
Math.sqrt(<value or set variable>) #square root Math::PI #pi to 15 digits Math::E #e to 15 digits
and finally, my least favorite, trig:
Code:
Math::sin(<value or set variable>) Math::cos(<value or set variable>) Math::tan(<value or set variable>)
For the methods involving advanced math and trig, you MUST capitalize Math. I cannot stress this enough.

Loops:

Spam time! Ruby, being as redundant as it is, has several ways to make loops. A few more common ones are while, .times and .each.
I'll explain how each of them work:

while:

Pretty simple. While the specified value is in the range of whatever condition you set, the code inside the statement will loop.
For an example: a simple counting program
Code:
i = 0 while i > 10 puts i i += 1 end
The += is a shorter version of i = i + 1

.times:

.times is what it sounds like; the number of times specified, it will iterate over the contained code.
Code:
i = 0 <value>.times do puts i i += 1 end

.each:

.each is used for arrays, ranges and Hashes, which we'll cover next time.
.each works as follows:
Code:
a = *(1..10) #I'm using a splat range because I'm lazy, I'll explain this next part. a.each do |num| #the |num| is for each value in the array num *= 2 end
since num is a variable while inside the .each class, you can treat it like one.




Thanks for reading, guys! I seem to be getting some positive feedback so I'll continue these for a while.
-Nightc||ed
It's often the outcasts, the iconoclasts ... those who have the least to lose because they
don't have much in the first place, who feel the new currents and ride them the farthest.

Reply