Contents
Control Statement
Ruby Decision Making (if, if-else, if-else-if, ternary)
Decision-making in programming is much like making choices in real life. In a program, certain blocks of code are executed based on whether a specific condition is true or false. Programming languages use control statements to manage the flow of execution depending on these conditions. These control structures guide the direction of execution, causing the program to branch or continue based on the current state. In Ruby, the if-else
structure helps in testing these conditions.
Types of Decision-Making Statements in Ruby:
1. if statement
2. if-else statement
3. if-elsif ladder
4. Ternary statement
1. if
Statement: In Ruby, the if
statement determines whether a block of code should be executed based on a condition. If the condition evaluates to true, the associated code is executed.
Syntax:
if (condition)
# code to be executed
end
Example:
# Ruby program to demonstrate the if statement
temperature = 30
# Check if temperature is above 25 degrees
if temperature > 25
puts "It's a warm day."
end
Output:
It's a warm day.
2. if-else Statement: The if-else
statement is used when one block of code should be executed if the condition is true, and another block should run if the condition is false.
Syntax:
if (condition)
# code if the condition is true
else
# code if the condition is false
end
Example:
# Ruby program to demonstrate if-else statement
time = 16
# Check if the time is past noon
if time > 12
puts "Good afternoon!"
else
puts "Good morning!"
end
Output:
Good afternoon!
3. if-elsif-else Ladder: This structure allows multiple conditions to be evaluated one after another. Once a true condition is found, the corresponding block of code is executed, and the remaining conditions are skipped.
Syntax:
if (condition1)
# code if condition1 is true
elsif (condition2)
# code if condition2 is true
else
# code if neither condition1 nor condition2 is true
end
Example:
# Ruby program to demonstrate if-elsif-else ladder
score = 85
if score < 50
puts "You failed."
elsif score >= 50 && score < 65
puts "You passed with a C grade."
elsif score >= 65 && score < 80
puts "You passed with a B grade."
elsif score >= 80 && score < 90
puts "You passed with an A grade."
else
puts "You passed with an A+ grade."
end
Output:
You passed with an A grade.
4. Ternary Operator: The ternary operator is a shorthand for simple if-else
statements. It evaluates a condition and returns one of two values based on whether the condition is true or false.
Syntax:
condition ? true_value : false_value
Example:
# Ruby program to demonstrate the ternary operator
age = 20
# Ternary operator to check if the person is an adult
status = (age >= 18) ? "Adult" : "Minor"
puts status
Output:
Adult
Ruby Loops (for, while, do..while, until)
Looping is an essential concept in programming, enabling the repeated execution of a block of code based on a specific condition. Ruby, a dynamic and flexible language, offers various looping constructs to handle iterations effectively. These loops help automate tasks that require repetitive actions within a program.
The primary types of loops in Ruby include:
1. while Loop
2. for Loop
3. do..while Loop
4. until Loop
1. while
Loop: In a while
loop, the condition is evaluated at the beginning of the loop, and the code block is executed as long as the condition is true. Once the condition becomes false, the loop terminates. This is known as an Entry-Controlled Loop since the condition is checked before executing the loop body. It’s commonly used when the number of iterations is unknown.
Syntax:
while condition [do]
# code to be executed
end
Example:
# Ruby program demonstrating the 'while' loop
counter = 3
# Using the while loop to print a message 3 times
while counter > 0
puts "Welcome to Ruby programming!"
counter -= 1
end
Output:
Welcome to Ruby programming!
Welcome to Ruby programming!
Welcome to Ruby programming!
2. for
Loop: The for
loop in Ruby functions similarly to the while
loop but has a more concise syntax, especially useful when the number of iterations is known in advance. It is often used to iterate over a range, array, or collection. This loop is also an Entry-Controlled Loop since the condition is evaluated before the loop begins.
Syntax:
for variable_name[, variable...] in expression [do]
# code to be executed
end
Example:
# Ruby program demonstrating the 'for' loop using a range
for num in 1..4 do
puts "Number: #{num}"
end
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Example 2: Iterating Over an Array
# Ruby program demonstrating the 'for' loop with an array
fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits do
puts fruit
end
Output:
Apple
Banana
Cherry
3. do..while
Loop: The do..while
loop is similar to the while
loop, but with one key difference: the condition is evaluated after the code block has been executed, ensuring that the loop runs at least once. This makes it an Exit-Controlled Loop.
Syntax:
loop do
# code to be executed
break if condition
end
Example:
# Ruby program demonstrating the 'do..while' loop
counter = 0
# The loop will run at least once
loop do
puts "Iteration #{counter + 1}"
counter += 1
break if counter == 3
end
Output:
Iteration 1
Iteration 2
Iteration 3
4. until
Loop: The until
loop in Ruby is the opposite of the while
loop. It continues executing as long as the given condition remains false, and stops once the condition becomes true. Like while
, this is also an Entry-Controlled Loop.
Syntax:
until condition [do]
# code to be executed
end
Example:
# Ruby program demonstrating the 'until' loop
counter = 5
# Using the until loop to print values until counter reaches 10
until counter == 10 do
puts counter
counter += 1
end
Output:
5
6
7
8
9
5. Class Variables: Class variables start with @@
and are shared across all instances of a class. They belong to the class itself rather than any individual instance. Class variables must be initialized before they are used. An uninitialized class variable will raise an error.
Example:
# Ruby program to illustrate Class Variables
class Library
# Class variable
@@book_count = 0
def initialize(title)
# Instance variable
@title = title
end
def display_title
puts "Book Title: #{@title}"
end
def add_book
# Increment the class variable
@@book_count += 1
puts "Total books: #@@book_count"
end
end
# Creating objects
book1 = Library.new("The Art of Ruby")
book2 = Library.new("Ruby on Rails Guide")
# Calling methods
book1.display_title
book1.add_book
book2.display_title
book2.add_book
Output:
Book Title: The Art of Ruby
Total books: 1
Book Title: Ruby on Rails Guide
Total books: 2
6. Global Variables: Global variables start with a $
sign and are accessible from anywhere in the Ruby program. They are not limited to a specific class or scope. By default, an uninitialized global variable has a nil
value. However, excessive use of global variables can make code difficult to debug and maintain.
Example:
# Ruby program to illustrate Global Variables
# Global variable
$global_count = 5
class FirstClass
def display_count
puts "Global count in FirstClass: #$global_count"
end
end
class SecondClass
def display_count
puts "Global count in SecondClass: #$global_count"
end
end
# Creating objects
obj1 = FirstClass.new
obj2 = SecondClass.new
# Calling methods
obj1.display_count
obj2.display_count
Output:
Global count in FirstClass: 5
Global count in SecondClass: 5
Case Statement Without a Value
In Ruby, you can use a case
statement without specifying a value. Instead, you can use the when
clauses to evaluate different conditions directly.
Example: Case Statement Without a Value
# Ruby program demonstrating case statement without a value
str = "HelloWorld123"
# Case statement evaluating different conditions
case
when str.match(/\d/)
puts "The string contains numbers."
when str.match(/[a-zA-Z]/)
puts "The string contains letters."
else
puts "The string contains neither letters nor numbers."
end
Example:
The string contains numbers.
Output:
Global variable in FirstClass is 20
Global variable in SecondClass is 20
Case Statement in Method Call
You can use a case
statement directly in a method call, where it will return a value just like any other method.
Example: Case Statement in a Method Call
# Ruby program demonstrating case statement in a method call
str = "4567"
# Case statement inside a method call to return a value
puts case
when str.match(/\d/)
"The string contains numbers."
when str.match(/[a-zA-Z]/)
"The string contains letters."
else
"The string contains neither numbers nor letters."
end
Output:
The string contains numbers.
Control Flow Statements in Ruby
Ruby provides several control flow statements in addition to loops, conditionals, and iterators. These statements allow altering the normal execution flow in a program, controlling how the code is executed based on conditions or specific cases.
Here’s a breakdown of some important Ruby control flow statements:
1. break
Statement: The break
statement is used to exit a loop prematurely when a certain condition is met. Typically used in loops such as while
, for
, and case
statements, it stops the execution of the loop as soon as the condition becomes true.
Syntax:
break
Example:
# Ruby program demonstrating the break statement
i = 1
# Using a while loop
while true
if i * 6 >= 30
break # Exit the loop if condition is met
end
puts i * 6
i += 1
end
Output:
6
12
18
24
2.next
Statement: The next
statement is used to skip the current iteration and move to the next one in a loop. It’s similar to the continue
statement in languages like C and Java.
Syntax:
next
Example:
# Ruby program demonstrating the next statement
# Using a for loop
for t in 0...10
if t == 5
next # Skip the iteration when t is 5
end
puts t
end
Output:
0
1
2
3
4
6
7
8
9
3. redo Statement: The redo statement restarts the current iteration of the loop without testing the loop’s condition again. Unlike next, which skips to the next iteration, redo causes the loop to restart the current one.
Syntax:
redo
Example:
# Ruby program demonstrating the redo statement
val = 0
while val < 4
puts val
val += 1
redo if val == 4 # Restart the loop when val equals 4
end
Output:
0
1
2
3
4
4.retry
Statement (Deprecated): The retry
statement was used in earlier versions of Ruby (before 1.9) to restart a loop or an iterator from the beginning. It has been removed in later versions, as it was considered a deprecated feature.
5.return
Statement: The return
statement is used to exit a method and optionally pass a value back to the caller. If no value is provided, it returns nil
.
Example:
# Ruby program demonstrating the return statement
def my_method
val1 = 100
val2 = 200
return val1, val2 # Returning multiple values
puts "This won't be executed"
end
result = my_method
puts result
Output:
100
200
6. throw
/catch
Statement: The throw
and catch
statements are used to create an advanced control flow structure. It’s like a multi-level break
that allows you to exit out of deeply nested loops or methods. throw
is used to break out, while catch
defines a label where control can be transferred.
Example:
# Ruby program demonstrating throw/catch control flow
def check_number(num)
throw :error if num < 10 # Exit the block if number is less than 10
puts "Number is greater than or equal to 10!"
end
catch :error do
check_number(15)
check_number(25)
check_number(5) # This will cause the throw statement to exit the block
end
puts "Code after catch block"
Output:
Number is greater than or equal to 10!
Number is greater than or equal to 10!
Code after catch block
Break and Next Statement
Break
statement:
In Ruby, the break
statement is used to stop the execution of a loop prematurely. It is often applied in loops like while
and for
, where it helps to exit the loop when a specific condition is met. Once the condition triggers the break
statement, the loop terminates, and the code continues after the loop.
Syntax:
break
Example:
# Ruby program demonstrating the break statement
i = 1
# Using a while loop
while true
puts i * 3 # Print multiples of 3
i += 1
if i * 3 >= 21
break # Exit the loop if the condition is met
end
end
Output:
3
6
9
12
15
18
Explanation: In this example, the loop prints multiples of 3. Once the value i * 3
becomes 21 or greater, the break
statement stops the loop.
Example:
# Another example demonstrating break statement
x = 0
# Using a while loop
while true
puts x # Print current value of x
x += 1
break if x > 3 # Stop the loop when x becomes greater than 3
end
Output:
0
1
2
3
next
Statement in Ruby
The next
statement is used to skip the rest of the current loop iteration and immediately proceed to the next iteration. It’s similar to the continue
statement in other programming languages like C or Python. This is useful when certain conditions inside a loop should cause the loop to skip to the next step without executing further code for that iteration.
Syntax:
next
Example:
# Ruby program demonstrating the next statement
for x in 0..6
if x + 1 < 4
next # Skip the current iteration if the condition is met
end
puts "Value of x is: #{x}" # Print the value of x for other cases
end
Output:
Value of x is: 3
Value of x is: 4
Value of x is: 5
Value of x is: 6
Working with Directories in Ruby
A directory is a location where files can be stored. In Ruby, the Dir
class and the FileUtils
module provide various methods for managing directories, while the File
class handles file operations. Double dot (..
) refers to the parent directory, and single dot (.
) refers to the current directory itself.
The Dir Class
The Dir
class allows access to and manipulation of directory structures in Ruby. It includes methods for listing directory contents, creating directories, changing directories, and more.
Features of the Dir Class
1. Creating Directories: The mkdir
method is used to create a new directory. It returns 0
if the directory is successfully created.
Syntax:
next
Examples:
# Ruby program demonstrating the next statement
for x in 0..6
if x + 1 < 4
next # Skip the current iteration if the condition is met
end
puts "Value of x is: #{x}" # Print the value of x for other cases
end
Output:
Value of x is: 3
Value of x is: 4
Value of x is: 5
Value of x is: 6
Ruby redo and retry Statement
redo
statement:
The redo
statement in Ruby is used to repeat the current iteration of a loop without re-evaluating the loop condition. It is useful when you want to retry the current iteration based on a specific condition. This statement can only be used inside loops.
Syntax:
redo
Example:
# Ruby program demonstrating redo statement
restart = false
# Using a for loop
for x in 2..20
if x == 15
if restart == false
# Print message when x is 15 for the first time
puts "Re-doing when x = #{x}"
restart = true
# Using redo statement to repeat the current iteration
redo
end
end
puts x
end
Output:
2
3
4
5
6
7
8
9
10
11
12
13
14
Re-doing when x = 15
15
16
17
18
19
20
retry
Statement in Ruby
The retry
statement is used to restart the entire loop from the beginning. It is typically used within a block that includes begin-rescue
error handling. The control jumps back to the start of the block or the loop, retrying the entire process. As of Ruby 1.9, the retry
statement is considered deprecated for regular loops but is still available in begin-rescue
blocks for exception handling.
Example :
# Ruby program demonstrating retry statement
# Using a do loop
10.times do |i|
begin
puts "Iteration #{i}"
raise if i > 2 # Raise an exception if i is greater than 2
rescue
# Retry the iteration if an exception is raised
retry
end
end
Output:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 3
Iteration 3
...