0% found this document useful (0 votes)
13 views5 pages

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)
13 views5 pages

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/ 5

Fundamentals of Arrays in Ruby

In Ruby, an array is an ordered collection of elements that can hold objects of any
data type, including other arrays.

Key Features of Ruby Arrays:


1. Heterogeneous Data: Ruby arrays can store elements of different types, such as
integers, strings, floats, or even other arrays.
2. Zero-based Indexing: Elements in a Ruby array are indexed starting from 0,
meaning the first element has an index of 0, the second element has an index of 1,
and so on.
3. Dynamic Size: Arrays in Ruby are dynamic, meaning they can grow or shrink in
size based on the operations performed on them.

Array Syntax
Arrays in Ruby are created by placing elements within square brackets ([]), and
elements are separated by commas.
numbers = [1, 2, 3, 4, 5]
names = ["Alice", "Bob", "Charlie"]
mixed = [1, "Hello", 3.14, true]

Basic Operations on Arrays


Accessing Elements You can access elements of an array using their index. Ruby uses
zero-based indexing.
numbers = [10, 20, 30, 40]
puts numbers[0] # Output: 10
puts numbers[2] # Output: 30

Modifying Elements You can modify an element at a specific index by assigning a new
value.
numbers = [10, 20, 30, 40]
numbers[1] = 25 # Change the second element
puts numbers # Output: [10, 25, 30, 40]

Adding Elements
Push: Add an element to the end of the array using push or <<.
numbers = [1, 2, 3]
numbers.push(4) # Adds 4 to the end
numbers << 5 # Adds 5 to the end
puts numbers # Output: [1, 2, 3, 4, 5]

Unshift: Add an element to the beginning of the array.


numbers = [2, 3, 4]
numbers.unshift(1) # Adds 1 to the beginning
puts numbers # Output: [1, 2, 3, 4]

Removing Elements
Pop: Remove the last element of the array.
numbers = [1, 2, 3, 4]
numbers.pop # Removes 4
puts numbers # Output: [1, 2, 3]

Shift: Remove the first element of the array.


numbers = [1, 2, 3, 4]
numbers.shift # Removes 1
puts numbers # Output: [2, 3, 4]

Array Length Use the length or size method to determine the number of elements in
an array.
numbers = [10, 20, 30, 40]
puts numbers.length # Output: 4

Slicing Arrays You can access a range of elements using slicing.


numbers = [10, 20, 30, 40, 50]
puts numbers[1, 3] # Output: [20, 30, 40]

Checking for Elements You can check whether a certain element exists in the array
using the include? method.
numbers = [10, 20, 30, 40]
puts numbers.include?(20) # Output: true

Iterating Over Arrays


You can use loops or iterators to process each element in an array.
Using each Method
numbers = [10, 20, 30, 40]
numbers.each do |number|
puts number
end

Multi-dimensional Arrays
Ruby arrays can store other arrays, allowing the creation of multi-dimensional
arrays.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
puts matrix[1][2] # Output: 6

Common Array Methods


Sort: Sorts the array in ascending order.
numbers = [3, 1, 4, 2]
puts numbers.sort # Output: [1, 2, 3, 4]

Reverse: Reverses the order of elements in the array.


numbers = [1, 2, 3, 4]
puts numbers.reverse # Output: [4, 3, 2, 1]

Join: Converts an array to a string with a specified delimiter.


words = ["hello", "world"]
puts words.join(" ") # Output: "hello world"

Flatten: Converts a multi-dimensional array into a one-dimensional array.


arr = [1, [2, 3], [4, 5]]
puts arr.flatten # Output: [1, 2, 3, 4, 5]

Examples:
1. Sort an array
numbers = [5, 3, 8, 1, 2]
sorted_numbers = numbers.sort

puts "Original array: #{numbers}"


puts "Sorted array: #{sorted_numbers}"

2. Reverse an array
letters = ['a', 'b', 'c', 'd']
reversed_letters = letters.reverse

puts "Original array: #{letters}"


puts "Reversed array: #{reversed_letters}"
3. To find max and min
numbers = [4, 7, 1, 9, 3]
max_value = numbers.max
min_value = numbers.min

puts "Array: #{numbers}"


puts "Maximum value: #{max_value}"
puts "Minimum value: #{min_value}"

4. To remove duplicate elements from an array


numbers = [1, 2, 2, 3, 3, 3, 4]
unique_numbers = numbers.uniq

puts "Original array: #{numbers}"


puts "Array with duplicates removed: #{unique_numbers}"

5. Program to Count the Occurrences of Each Element in an Array


numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
counts = numbers.tally

puts "Array: #{numbers}"


puts "Element counts: #{counts}"

6. include?
colors = ["red", "green", "blue"]

if colors.include?("green")
puts "Green is in the array"
else
puts "Green is not in the array"
end

String Methods:
1. length / size
Returns the number of characters in a string.
str = "Hello, Ruby!"
puts str.length # Output: 12
puts str.size # Output: 12

2. upcase / downcase
upcase: Converts all characters to uppercase.
downcase: Converts all characters to lowercase.
str = "Hello, Ruby!"
puts str.upcase # Output: "HELLO, RUBY!"
puts str.downcase # Output: "hello, ruby!"

3. capitalize
Capitalizes the first character of the string and converts the rest to lowercase.
str = "ruby programming"
puts str.capitalize # Output: "Ruby programming"

4. reverse
Reverses the characters in the string.
str = "Ruby"
puts str.reverse # Output: "ybuR"

5. include?
Checks if a given substring is present in the string. Returns true or false
str = "Hello, Ruby!"
puts str.include?("Ruby") # Output: true
puts str.include?("Java") # Output: false

6. gsub
Substitutes all occurrences of a pattern with a given replacement.
str = "I love Ruby, Ruby is awesome!"
new_str = str.gsub("Ruby", "Python")
puts new_str # Output: "I love Python, Python is awesome!"

7. split
Splits the string into an array based on a delimiter (space by default).
str = "apple,banana,cherry"
fruits = str.split(",")
puts fruits # Output: ["apple", "banana", "cherry"]

8. strip / lstrip / rstrip


strip: Removes leading and trailing whitespace.
lstrip: Removes leading whitespace.
rstrip: Removes trailing whitespace.
str = " Hello, Ruby! "
puts str.strip # Output: "Hello, Ruby!"
puts str.lstrip # Output: "Hello, Ruby! "
puts str.rstrip # Output: " Hello, Ruby!"

9. chomp
Removes the newline character (\n) from the end of the string.
str = "Hello, Ruby!\n"
puts str.chomp # Output: "Hello, Ruby!"

10. concat
Appends one string to another.
str1 = "Hello, "
str2 = "Ruby!"
puts str1.concat(str2) # Output: "Hello, Ruby!"

11. start_with? / end_with?


start_with?: Checks if the string starts with a given substring.
end_with?: Checks if the string ends with a given substring.
str = "Hello, Ruby!"
puts str.start_with?("Hello") # Output: true
puts str.end_with?("Ruby!") # Output: true

12. index
Returns the index of the first occurrence of a substring, or nil if not found.
str = "Hello, Ruby!"
puts str.index("Ruby") # Output: 7
puts str.index("Java") # Output: nil

13. replace
Replaces the contents of the string with another string.
str = "Hello, Ruby!"
str.replace("Hi, Python!")
puts str # Output: "Hi, Python!"

14. slice
Extracts a portion of the string based on the index or range.
str = "Hello, Ruby!"
puts str.slice(0, 5) # Output: "Hello"
puts str.slice(7..10) # Output: "Ruby"

15. to_i / to_f


to_i: Converts the string to an integer.
to_f: Converts the string to a floating-point number.
str1 = "123"
str2 = "45.67"
puts str1.to_i # Output: 123
puts str2.to_f # Output: 45.67

16. empty?
Returns true if the string is empty, otherwise false.
str1 = ""
str2 = "Ruby"
puts str1.empty? # Output: true
puts str2.empty? # Output: false

17. sub
Replaces the first occurrence of a pattern with a given replacement.
str = "I love Ruby, Ruby is awesome!"
new_str = str.sub("Ruby", "Python")
puts new_str # Output: "I love Python, Ruby is awesome!"

18. count
Counts the number of occurrences of a specific character or set of characters.
str = "abracadabra"
puts str.count("a") # Output: 5
puts str.count("bc") # Output: 4

19. delete
Deletes all occurrences of a specific character or set of characters from the
string.
str = "abracadabra"
puts str.delete("a") # Output: "brcdbr"

20. insert
Inserts a string at the specified index.
str = "Hello Ruby!"
str.insert(5, ",")
puts str # Output: "Hello, Ruby!"

You might also like