0% found this document useful (0 votes)
15 views

LU 36-39 Ruby Basic-Cs-Arrays

LU 36-39 Ruby Basic-cs-arrays

Uploaded by

Muthamil0593
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

LU 36-39 Ruby Basic-Cs-Arrays

LU 36-39 Ruby Basic-cs-arrays

Uploaded by

Muthamil0593
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 15

Datatypes in Ruby:

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

9. Regular Expressions (Regex)


Patterns used to match strings.
Example: /[a-zA-Z]/

10. Classes and Objects


Custom data types defined using classes. An instance of a class is an object.
Example: class Person; end

New operators in Ruby:


The spaceship operator <=> returns:
1 if the left side is greater,
0 if both are equal,
-1 if the left side is smaller.

* - 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

Sum of n numbers using while


print "Enter a positive integer n: "
n = gets.chomp.to_i
sum = 0
i = 1
while i <= n
sum += i
i += 1
end
puts "The sum of the first #{n} natural numbers is #{sum}."

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

puts "Blast off!"

Simple Calc:
puts "Simple Arithmetic Calculator"
puts "Available operations:"
puts "1. Addition (+)"
puts "2. Subtraction (-)"
puts "3. Multiplication (*)"
puts "4. Division (/)"

print "Enter your choice (1/2/3/4): "


choice = gets.chomp.to_i

if choice >= 1 && choice <= 4


print "Enter the first number: "
num1 = gets.chomp.to_f
print "Enter the second number: "
num2 = gets.chomp.to_f

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

puts "Result: #{num1} #{operator} #{num2} = #{result}"


else
puts "Invalid choice. Please select a valid operation (1/2/3/4)."
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!

puts "Enter a number:"


input = gets.chomp.to_i

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

Search for an element


numbers = [1, 2, 3, 4, 5]
element_to_find = 3
found = false

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

2. Method with Parameters:


def greet(name)
puts "Hello, #{name}!"
end

greet("Alice")
greet("Bob")

3. Method with Default Parameter:


def greet(name = "stranger")
puts "Hello, #{name}!"
end
greet("Alice")
greet

4. Method with Return Value:


def add(a, b)
return a + b
end

result = add(5, 3)
puts "The sum is #{result}"

5. Method with Multiple Return Values (Using an Array):


def get_name_and_age
name = "Alice"
age = 30
return [name, age]
end

name, age = get_name_and_age


puts "Name: #{name}, Age: #{age}"

6. (* params) -This is often referred to as a "splat" parameter, and it allows you


to pass any number of arguments to the method.

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()

7. With keyword Parameters


def describe_person(name:, age:, city:)
puts "#{name} is #{age} years old and lives in #{city}."
end

describe_person(name: "Alice", age: 30, city: "New York")


describe_person(name: "Bob", age: 25, city: "San Francisco")

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? }

# Custom descending sort


for i in 0..even_numbers.length - 1
for j in 0..even_numbers.length - i - 2
if even_numbers[j] < even_numbers[j + 1]
# Swap elements
temp = even_numbers[j]
even_numbers[j] = even_numbers[j + 1]
even_numbers[j + 1] = temp
end
end
end

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

original_array = [5, 8, 2, 10, 3, 6, 7]


result = filter_and_sort_evens(original_array)
puts "Original Array: #{original_array}"
puts "Even Numbers Sorted in Descending Order: #{result}"

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? }

puts evens # Output: [2, 4, 6]

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

# Creating instances (objects) of the Dog class


dog1 = Dog.new("Buddy", "Golden Retriever")
dog2 = Dog.new("Max", "German Shepherd")

# Calling the bark method on the objects


dog1.bark
dog2.bark

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

class MySubClass < MyClass


def call_protected_method
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

Inheritance is a fundamental concept in object-oriented programming (OOP) that


allows you to create new classes based on existing classes. In Ruby, you can
achieve inheritance by defining a new class that inherits the properties and
behaviors (methods and attributes) from an existing class. The existing class is
referred to as the "parent class" or "superclass," and the new class is the "child
class" or "subclass."

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

class Car < Vehicle


def start_engine
super # Calls the start_engine method of the parent class
puts "Turning the ignition key to start the car."
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

# Base class Shape


class Shape
def calculateArea
raise NotImplementedError, "Subclasses must implement calculateArea method"
end
end

# Derived class Circle


class Circle < Shape
def initialize(radius)
@radius = radius
end

def calculateArea
Math::PI * @radius**2
end
end

# Derived class Rectangle


class Rectangle < Shape
def initialize(length, width)
@length = length
@width = width
end

def calculateArea
@length * @width
end
end

# Derived class Triangle


class Triangle < Shape
def initialize(base, height)
@base = base
@height = height
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

# Call the method and provide a block of code to execute


print_message do
puts "This is the block of code called by yield"
end

def yieldExample
yield 5
puts "You are inside the method yieldExample"
yield 100
end

yieldExample {|i| puts "This is the iteration number #{i}"}

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):007:0> y="welcome to IP"


irb(main):010:0> z=y.split('')
=> ["welcome", "to", "IP"]
irb(main):011:0> z=y.split(' ',2)
=> ["welcome", "to IP"]

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

x = "Hello, World. How are you?"

=> "Hello, World. How are you?"


irb(main):013:0> result = x.split(/[ .,]\s*/)
=> ["Hello", "World", "How", "are", "you?"]

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.

\d matches a digit (0-9).

{4} specifies that exactly four digits should be present for the year.

- matches the hyphen character.

{2} specifies that exactly two digits should be present for the month.

Another - for the hyphen.


{2} specifies that exactly two digits should be present for the day.

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.

[\w+\-.]+ matches one or more word characters (letters, digits, or underscores),


plus signs (+), or hyphens (-). This part is for the username.

@ 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).

[a-z]+ matches one or more lowercase letters for the 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.

text = "This, is a sample sentence. With spaces, and, commas."


tokens = text.split(/[ ,]+/)

# tokens will be ["This", "is", "a", "sample", "sentence.", "With", "spaces",


"and", "commas."]

text = "apple orange banana cherry grape"


fruits = text.split(/\s/, 3)

# fruits will be ["apple", "orange", "banana cherry grape"]


/\s/ is a regular expression pattern that matches whitespace characters (spaces,
tabs, and line breaks). This pattern is used as the delimiter to split the string.
3 is the limit argument that restricts the number of splits.

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

text = "Visit my website: http://www.example.com"


match_data = text.match(/(http:\/\/\S+)/)
if match_data
url = match_data[1]
puts "URL: #{url}"
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.

text = "I like Ruby, Ruby is great!"


result = text.sub("Ruby", "Python")
puts result
# Output: "I like Python, Ruby is great!"

The gsub method is used to replace all occurrences 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.
text = "I like Ruby, Ruby is great!"
result = text.gsub("Ruby", "Python")
puts result
# Output: "I like Python, Python is great!"

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.

2. `rails db:migrate`: This command is used to run database migrations. Migrations


are used to evolve your database schema over time. When you add new tables or
modify existing ones, you create a migration and then use this command to apply
those changes to the database.

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?

text = "Important dates: 2023-10-26, 2023-11-15, and 2023-12-05"


pattern = /\d{4}-\d{2}-\d{2}/

matches = text.scan(pattern)
puts matches

text = "Contact us at +1-555-555-5555 or 123-456-7890"


pattern = /\+?\d{1,3}-\d{3}-\d{3}-\d{4}/

matches = text.scan(pattern)
puts matches

text = "I love #programming and #coding!"


pattern = /#\w+/

matches = text.scan(pattern)
puts matches

text = "Custom patterns: ABC123, XYZ456, and PQR789."


pattern = /[A-Z]{3}\d{3}/

matches = text.scan(pattern)
puts matches

text = "Server IPs: 192.168.1.1 and 10.0.0.1"


pattern = /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/

matches = text.scan(pattern)
puts matches

text = "Apples, bananas, and cherries are delicious."


pattern = /\b[A-Ba-b]\w+\b/

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."

3digits Ex: fsdfs452fdsf


3character3digits ABC456
Hashtag jsdojfo #India
Starting with A or B
Exactly 4 digit input

You might also like