Ruby Condition,Loop Statement
The previous part 1 was introduction and basic of ruby. This part is going to be about condition and looping statement along with array and hash .
Conditional Statement
If
Ruby’s if
statement takes an expression, which is just a fancy word for something that has a value that evaluates to either true
or false
. If that expression is true
, Ruby executes the block of code that follows the if
. If it's not true (that is, false
), Ruby doesn't execute that block of code: it skips it and goes on to the next thing.
Ruby doesn’t care about whitespace (spaces and blank lines), so the indentation of the print statement isn’t necessary. However, it’s a convention that Rubyists (Ruby enthusiasts) follow, so it’s good to get in the habit now. The block of code following an if
should be indented two spaces.
Else
The partner to the if
statement is the else
statement. An if
/else
statement says to Ruby: "If this expression is true, run this code block; otherwise, run the code after the else
statement."
Elsif
What if you want more than two options, though? It’s elsif
to the rescue! The elsif
statement can add any number of alternatives to an if
/else
statement.
x = 1
if x > 2
puts "x is greater than 2"
elsif x <= 2 and x!=0
puts "x is 1"
else
puts "I can't guess the number"
end
Unless
Sometimes you want to use control flow to check if something is false, rather than if it’s true. You could reverse your if
/else
, but Ruby will do you one better: it will let you use an unless
statement.
x = 1
unless x>=2
puts "x is less than 2"
else
puts "x is greater than 2"
end
In Ruby, we assign values to variables using =
, the assignment operator. But if we've already used =
for assignment, how do we check to see if two things are equal? Well, we use ==
, which is a comparator (also called a relational operator). ==
means "is equal to." When you type
Logical Operators
You can also use logical or boolean operators. Ruby has three: and (&&
), or (||
), and not (!
). Boolean operators result in boolean values: true
or false
.
The boolean operator and, &&
, only results in true
when both expression on either side of &&
are true
.
Ruby also has the or operator (||
). Ruby's ||
is called an inclusive or because it evaluates to true
when one or the other or both expressions are true.
Ruby also has the not operator(!). Ruby’s ! is used to exchange the boolean value. If you’re false
you're now true
. if you're true
you're now false.
Loop Statement
The ‘While’ Loop
Sometimes you want to repeat an action in Ruby while a certain condition is true, but you don’t know how many times you’ll have to repeat that action. A good example would be prompting a user for a certain type of input: if they insist on giving you the wrong thing, you may have to re-ask them several times before you get the kind of input you’re looking for.
To accomplish this, we use something called a while
loop. It checks to see if a certain condition is true, and while
it is, the loop keeps running. As soon as the condition stops being true, the loop stops!
i = 0
num = 5while i < num do
puts("value of i = #{i}" )
i +=1
end
The ‘Until’ Loop
The complement to the while
loop is the until
loop. It's sort of like a backward while
:
i = 0
num = 5until i > num do
puts("Inside the loop i = #{i}" )
i +=1
end
Here i+=1
is a unary operator which is also represent as i=i+1.
Similarly, +=
, -=
, *=
, and /=
are also unary operators.
And #{i}
is called String Interpolation
The ‘For’ Loop
for i in 0..5
puts "Value of local variable is #{i}"
end
for i in 1...10
means "go up to but don't include 10
." If we use two dots, this tells Ruby to include the highest number in the range
The .times
method is like a super compact for
loop: it can perform a task on each item in an object a specified number of times.
10.times{print “hello” }
Next!
The next
keyword can be used to skip over certain steps in the loop. For instance, if we don't want to print out the even numbers, we can write:
for i in 1..5
next if i % 2 == 0
puts i
end
Saving Multiple Values
In Ruby, we can pack multiple values into a single variable using an array. An array is just a list of items between square brackets, like so: [1, 2, 3, 4]
. The items don't have to be in order—you can just as easily have [10, 31, 19, 400]
.
The .each Iterator
The loop
iterator is the simplest, but also one of the least powerful. A more useful iterator is the .each
method, which can apply an expression to each element of an object, one at a time. The syntax looks like this:
names = ['Foo', 'Bar', 'Baz']
names.each { |item|
puts item
}
The Case Statement
if
and else
are powerful, but we can get bogged down in if
s and elsif
s if we have a lot of conditions to check. Thankfully, Ruby provides us with a concise alternative: the case
statement. The syntax looks like this:
case language
when "JS"
puts "Websites!"
when "Python"
puts "Science!"
when "Ruby"
puts "Web apps!"
else
puts "I don't know!"
end
An even more concise version of if
/else
is the ternary conditional expression. It's called "ternary" because it takes three arguments: a boolean, an expression to evaluate if the boolean is true
, and an expression to evaluate if the boolean is false
.
The syntax looks like this:
boolean ? Do this if true: Do this if false
Data structure
Arrays: Each element in the array has what’s called an index. The first element is at index 0
, the next is at index 1
, the following is at index 2
, and so on. We can access elements of the array directly.
names = Array.new(20)
puts names.size # This returns 20
puts names.length # This also returns 20
Arrays of Arrays
Arrays of arrays are called multidimensional arrays, since the act of adding more arrays expands the array out of its string-like shape. For instance, the array in the editor is a two-dimensional array.
multi_d_array = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
Introduction to Hashes
Hashes are sort of like JavaScript objects or Python dictionaries. Hash is a collection of key-value pairs. Hash syntax looks like this:
H = Hash["a" => 100, "b" => 200]puts "#{H['a']}"
puts "#{H['b']}"
The hash syntax you’ve seen so far (with the =>
symbol between keys and values) is sometimes nicknamed the hash rocket style.