![]() |
|
A beginners guide to Ruby, Part 3 - Printable Version +- Sinisterly (https://sinister.li) +-- Forum: Coding (https://sinister.li/Forum-Coding) +--- Forum: Coding (https://sinister.li/Forum-Coding--71) +--- Thread: A beginners guide to Ruby, Part 3 (/Thread-A-beginners-guide-to-Ruby-Part-3) |
A beginners guide to Ruby, Part 3 - Inori - 04-01-2015 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 statementThe 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>
endMath: Math in Ruby is pretty simple, but extremely useful. the operators are as follows: Code: + #addition
- #subtraction
* #multiplication
/ #division
% #modulus (divides and returns remainder)
** #exponentCode: Math.sqrt(<value or set variable>) #square root
Math::PI #pi to 15 digits
Math::E #e to 15 digitsCode: Math::sin(<value or set variable>)
Math::cos(<value or set variable>)
Math::tan(<value or set variable>)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.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
endThanks for reading, guys! I seem to be getting some positive feedback so I'll continue these for a while. -Nightc||ed |