LU 36-39 Ruby Basic-Cs-Arrays
LU 36-39 Ruby Basic-Cs-Arrays
Ruby has several built-in data types, each serving different purposes.
1. Numbers
Integer: Whole numbers, both positive and negative.
Example: 10, -5
Float: Decimal numbers.
Example: 3.14, -0.99
2. Strings
Used to represent text, enclosed in single or double quotes.
Example: 'hello', "world"
3. Symbols
Immutable, reusable names, often used as keys for hashes or identifiers.
Example: :name, :status
4. Booleans
Represents truth values: true or false.
Example: true, false
5. Arrays
Ordered collections of objects, which can include multiple data types.
Example: [1, 2, 'apple', :symbol]
6. Hashes
Key-value pairs (dictionaries), similar to arrays but with custom keys.
Example: { :name => "John", :age => 30 } or { name: "John", age: 30 }
7. Nil
Represents "nothing" or "no value". Ruby’s way of handling null.
Example: nil
8. Ranges
Represents a sequence of values, defined by a starting and ending point.
Example: (1..5) or (1...5)
.. Inclusive range (1..5) 1, 2, 3, 4, 5
... Exclusive range (1...5) 1, 2, 3, 4
* - Repetition Operator
String repetition: "Hello" * 3 → "HelloHelloHello"
Control Statements:
`if` / `else`
`elsif`
`case` / `when`
`unless`
`while` / `until`
`for`
`break` / `next`
`return`
if Statement:
The if statement is used to execute a block of code only if a specified condition
is true.
if condition
# Code to be executed if the condition is true
else
# Code to be executed if the condition is false
end
Example:
age = 18
if age >= 18
puts "You are an adult."
else
puts "You are not yet an adult."
end
unless Statement:
The unless statement is the opposite of if. It executes a block of code if a
specified condition is false.
Syntax:
unless condition
# Code to be executed if the condition is false
else
# Code to be executed if the condition is true
end
Example:
temperature = 25
unless temperature >= 30
puts "It's a cool day."
else
puts "It's a hot day."
end
for-in
numbers = [1, 2, 3, 4, 5]
for number in numbers
puts number
end
Until
count = 5
until count == 0
puts "Countdown: #{count}"
count -= 1
end
Simple Calc:
puts "Simple Arithmetic Calculator"
puts "Available operations:"
puts "1. Addition (+)"
puts "2. Subtraction (-)"
puts "3. Multiplication (*)"
puts "4. Division (/)"
case choice
when 1
result = num1 + num2
operator = "+"
when 2
result = num1 - num2
operator = "-"
when 3
result = num1 * num2
operator = "*"
when 4
if num2 != 0
result = num1 / num2
operator = "/"
else
puts "Cannot divide by zero."
exit
end
end
Arrays Methods:
shift, unshift ---> left end remove/add---> l1.shift / l1.unshift(10)
push, pop ----> right end add/remove---> l1.push(10) / l1.pop
concat -->l1.concat(l2) / l1 + l2
reverse/ reverse!
include? ---> search method---> true/ flase
sort, sort!
case input
when 1..10
puts "Input is in the range 1 to 10."
when 11..20
puts "Input is in the range 11 to 20."
when 21..30
puts "Input is in the range 21 to 30."
else
puts "Input is outside the specified ranges."
end
numbers.each do |number|
if number == element_to_find
found = true
break
end
end
if found
puts "#{element_to_find} found in the array."
else
puts "#{element_to_find} not found in the array."
end
Methods:
1. Method without Parameters:
def say_hello
puts "Hello, world!"
end
say_hello
greet("Alice")
greet("Bob")
result = add(5, 3)
puts "The sum is #{result}"
def fun1(*params)
puts "The number of arguments is:#{params.length}"
puts "The arguments are: #{params.inspect}"
end
fun1(1, 2, 3)
fun1("apple", "banana", "cherry", "date")
fun1(42)
fun1()
Sample Exercises:
Write a Ruby function that takes an array of integers as input and returns a new
array with all the even numbers from the original array, sorted in descending
order.
def custom_sort_descending(arr)
# Filter even numbers
even_numbers = arr.select { |num| num.even? }
return even_numbers
end
# Example usage:
original_array = [5, 8, 2, 10, 3, 6, 7]
result = custom_sort_descending(original_array)
puts "Original Array: #{original_array}"
puts "Even Numbers Sorted in Descending Order: #{result}"
or
def filter_and_sort_evens(arr)
even_numbers = arr.select { |num| num.even?}
sorted_evens = even_numbers.sort
reversed_sorted_evens = sorted_evens.reverse
reversed_sorted_evens
end
or
def filter_and_sort_evens(arr)
arr.select { |num| num.even? }.sort.reverse
def even_numbers_descending
numbers = []
puts "Enter numbers one by one. Type '0' when finished:"
loop do
input = gets.chomp.to_i
break if input == 0
numbers.push(input)
end
numbers.select { |num| num.even? }.sort.reverse
end
result = even_numbers_descending
puts "Even numbers in descending order: #{result}"
The .select method in Ruby is used to filter elements from an array based on a
specific condition. It iterates over each element and returns a new array
containing only the elements for which the given block evaluates to true.
numbers = [1, 2, 3, 4, 5, 6]
evens = numbers.select { |num| num.even? }
Class:
A class is a blueprint or a template for creating objects. It defines the structure
and behavior of objects that will be created based on it. In Ruby, you define a
class using the class keyword.
Instance Variable:
Instance variables are used to store the state or attributes of an object. They are
prefixed with the @ symbol. Each instance of a class can have its own values for
these instance variables.
Constructor:
In Ruby, the constructor method is named initialize. It is called when a new object
is created from a class.
class Dog
def initialize(name, breed)
@name = name
@breed = breed
end
def bark
puts "#{@name} the #{@breed} barks!"
end
end
Access Control:
access control is used to determine the visibility and accessibility of methods and
variables within a class. Ruby provides three levels of access control: public,
protected, and private.
Public:
Public methods and variables can be accessed from anywhere, both inside and outside
the class.
By default, all methods in Ruby are public unless specified otherwise.
Public methods can be called using an instance of the class.
Example:
class MyClass
def public_method
puts "This is a public method."
end
def another_public_method
puts "This is another public method."
end
end
obj = MyClass.new
obj.public_method
Protected:
Protected methods and variables can only be accessed within the class and its
subclasses.
They are often used when you want to provide controlled access to certain methods,
especially in the context of inheritance.
Example:
class MyClass
protected
def protected_method
puts "This is a protected method."
end
end
obj = MySubClass.new
obj.call_protected_method
Private:
Private methods and variables can only be accessed within the class. They cannot be
called on an instance of the class.
Private methods are often used for implementation details that should not be
exposed to external code.
Example:
class MyClass
private
def private_method
puts "This is a private method."
end
end
obj = MyClass.new
obj.private_method # This will result in an error
You can access the methods and attributes of the parent class from the child class
using the super keyword.
class Vehicle
def start_engine
puts "Starting the vehicle's engine."
end
end
class Bike < Vehicle
def start_engine
super # Calls the start_engine method of the parent class
puts "Pedaling to start the bike."
end
end
vehicle = Vehicle.new
vehicle.start_engine # Outputs: Starting the vehicle's engine
bike = Bike.new
bike.start_engine # Outputs: Starting the vehicle's engine\nPedaling to start
the bike
car = Car.new
car.start_engine # Outputs: Starting the vehicle's engine\nTurning the
ignition key to start the car
def calculateArea
Math::PI * @radius**2
end
end
def calculateArea
@length * @width
end
end
def calculateArea
0.5 * @base * @height
end
end
circle = Circle.new(5)
circle_area = circle.calculateArea
puts "Circle Area: #{circle_area}"
rectangle = Rectangle.new(4, 6)
rectangle_area = rectangle.calculateArea
puts "Rectangle Area: #{rectangle_area}"
triangle = Triangle.new(3, 8)
triangle_area = triangle.calculateArea
puts "Triangle Area: #{triangle_area}"
The yield keyword is used to call a block of code that's associated with a method.
It's a way to pass a block of code to a method and execute it within the method's
context.
Yield Example:
# Define the print_message method
def print_message
puts "This is the start of the method"
yield
puts "This is the end of the method"
end
def yieldExample
yield 5
puts "You are inside the method yieldExample"
yield 100
end
we have defined a method called yieldExample and inside this method we have
written some puts statement and the yield statement. In this example we are calling
the method with argument as the number and printing the number when calling
yieldExamle method without passing any argument to it. When the Yield example
method gets called it will print the output written inside the method calling block
and block will read the number variable of its block from the yield statements.
def arithmetic(a, b)
yield(a, b)
end
puts "The sum of the two numbers is #{arithmetic(8, 2) { |a, b| a + b }}" #
addition of two number
puts "The multiplication of the two numbers is #{arithmetic(8, 2) { |a, b| a *
b }}" # multiplication of two numbers
puts "The subtraction of the two numbers is #{arithmetic(8, 2) { |a, b| a - b }}" #
subtraction of two numbers
puts "The division of the two numbers is #{arithmetic(8, 2) { |a, b| a / b }}" #
division of two numbers
irb(main):001:0> x="sample"
=> "sample"
irb(main):002:0> x =~ /m/
=> 2
irb(main):003:0> x =~ /mp/
=> 2
irb(main):004:0> x =~ /mpa/
=> nil
irb(main):015:0> y
=> "welcome to IP"
irb(main):016:0> y.match(/to/)
=> #<MatchData "to">
irb(main):017:0> y.match(/too/)
=> nil
date = "2023-10-21"
if date.match(/\A\d{4}-\d{2}-\d{2}\z/)
puts "Valid date format"
else
puts "Invalid date format"
end
^ and $ (or \A and \z) ensure that the regular expression matches the entire
string, not just a part of it.
{4} specifies that exactly four digits should be present for the year.
{2} specifies that exactly two digits should be present for the month.
email.match(/\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i)
\A and \z (or ^ and $) ensure that the regular expression matches the entire
string.
@ matches the "@" symbol, which separates the username from the domain.
[a-z\d\-.]+ matches one or more lowercase letters, digits, hyphens (-), or periods
(.) in the domain name.
\. matches the period (.) character, which separates the domain name from the top-
level domain (TLD).
The i at the end of the regular expression (outside the forward slashes) makes the
pattern case-insensitive, so it will match both uppercase and lowercase letters in
the email address.
Match Data :
date_string = "2023-10-21"
match_data = date_string.match(/(\d{4})-(\d{2})-(\d{2})/)
if match_data
year = match_data[1]
month = match_data[2]
day = match_data[3]
puts "Year: #{year}, Month: #{month}, Day: #{day}"
end
In Ruby, sub and gsub are methods for string manipulation that are used to find and
replace substrings in a string.
The sub method is used to replace the first occurrence of a specified substring in
a string with another substring. It takes two arguments: the substring to find and
the substring to replace it with.
However, sub and gsub have mutator versions, named sub! and gsub!.
In a Ruby on Rails application, the `rails db` command is used to interact with the
application's database. This command is typically followed by various subcommands
to perform tasks like creating, migrating, seeding, and more. Here are some common
subcommands used with `rails db`:
1. `rails db:create`: This command is used to create a new database for your Rails
application. It will create a database based on the configuration specified in your
`config/database.yml` file.
3. `rails db:rollback`: This command is used to roll back the last database
migration. It can be useful if you need to undo the most recent changes to your
database schema.
4. `rails db:seed`: This command is used to run the seed data defined in your
application's `db/seeds.rb` file. Seed data is often used to populate the database
with initial or default data.
5. `rails db:drop`: This command is used to delete the database for your Rails
application. Be cautious when using this command, as it will remove all data in the
database.
6. `rails db:schema:load`: This command loads the schema from the `db/schema.rb`
file into the database. It's an alternative way to set up the database structure
without running migrations.
7. `rails db:reset`: This command combines the `db:drop`, `db:create`,
`db:migrate`, and `db:seed` commands, effectively resetting the database to its
initial state.
These are some of the common subcommands used with `rails db`. The specific command
you use will depend on what you need to do with your Rails application's database.
Remember to run these commands in your Rails application's root directory.
Imagine you have a base class called Shape with a method calculateArea(). You also
have several derived classes like Circle, Rectangle, and Triangle. How would you
implement the calculateArea() method in each derived class to provide the specific
area calculation for that shape?
matches = text.scan(pattern)
puts matches
matches = text.scan(pattern)
puts matches
matches = text.scan(pattern)
puts matches
matches = text.scan(pattern)
puts matches
matches = text.scan(pattern)
puts matches
matches = text.scan(pattern)
puts matches
\bword\b will match the whole word "word" and not parts of other words that contain
"word" (e.g., "keyword" or "password" will not match).
\b\d{4}\b will match exactly four-digit numbers as whole words, like "1234" but not
"12345."