Data Types
Ruby is a dynamically typed language, meaning that you don't need to explicitly declare the data type of a variable. Instead, Ruby infers the data type based on the value assigned to the variable.
Integer
It represents whole numbers.
number = 58
Float
It represents decimal numbers.
float_number = 3.14
Boolean
It represents true or false values.
is_true = true
is_false = false
String
It represents sequences of characters.
text = "Hello, Ruby!"
Ruby provides a variety of operations you can perform on strings.
# Concatenation
str1 = "Hello"
str2 = "World"
concatenated_str = str1 + ", " + str2
puts concatenated_str # => Hello, World
# Interpolation
name = "Alice"
greeting = "Hello, #{name}!"
puts greeting # => Hello, Alice!
# Length
length = "This is a string".length
puts length # => 16
# Concatenation using <<
str3 = "Hello"
str3 << ", " << "World"
puts str3 # => Hello, World
# Reversing a string
reversed_str = "Ruby".reverse
puts reversed_str # => ybuR
# Uppercase and lowercase
uppercase_str = "lite".upcase
puts uppercase_str # => LITE
lowercase_str = "RANK".downcase
puts lowercase_str # => rank
# Checking if a string contains a substring
contains_substring = "Hello, World!".include?("World")
puts contains_substring # => true
# Substring extraction
substring = "Hello, World!"[7..11]
puts substring # => World
# Splitting a string into an array
word_array = "This is a sentence.".split
puts word_array.inspect # => ["This", "is", "a", "sentence."]
# Stripping whitespace
whitespace_str = " Trim me! "
trimmed_str = whitespace_str.strip
puts trimmed_str # => Trim me!
Symbol
It represents lightweight and immutable identifiers, which are often used as keys in hashes.
# Creating symbols
symbol1 = :apple
symbol2 = :orange
# Comparing symbols
puts symbol1 == symbol2 # => false
# Converting a string to a symbol
string = "banana"
symbol_from_string = string.to_sym
puts symbol_from_string # => :banana
# Converting a symbol to a string
symbol = :grape
string_from_symbol = symbol.to_s
puts string_from_symbol # => "grape"
# Checking if a symbol exists in an array
symbols = [:apple, :orange, :banana]
puts symbols.include?(:apple) # => true
puts symbols.include?(:watermelon) # => false
# Using symbols as keys in a hash
fruit_counts = { :apple => 3, :orange => 5, :banana => 2 }
puts fruit_counts[:orange] # => 5
# Iterating over symbols in a hash
fruit_counts.each do |fruit, count|
puts "#{fruit}: #{count}"
end
# Output:
# apple: 3
# orange: 5
# banana: 2
Nil
It represents the absence of a value.
empty_value = nil
Array
It represents an ordered collection of items.
numbers = [1, 2, 3, 4, 5]
Arrays in Ruby offer various operations for managing and manipulating collections of elements.
# Accessing elements
puts numbers[0] # => 1
puts numbers[-1] # => 5 (last element)
# Adding elements to the end of an array
numbers.push(6)
puts numbers.inspect # => [1, 2, 3, 4, 5, 6]
# Adding elements to the beginning of an array
numbers.unshift(0)
puts numbers.inspect # => [0, 1, 2, 3, 4, 5, 6]
# Removing elements from the end of an array
removed_element = numbers.pop
puts removed_element # => 6
puts numbers.inspect # => [0, 1, 2, 3, 4, 5]
# Removing elements from the beginning of an array
removed_element = numbers.shift
puts removed_element # => 0
puts numbers.inspect # => [1, 2, 3, 4, 5]
# Checking if an array includes a specific element
puts numbers.include?(3) # => true
# Finding the index of an element
index = numbers.index(4)
puts index # => 3
# Reversing an array
reversed_numbers = numbers.reverse
puts reversed_numbers.inspect # => [5, 4, 3, 2, 1]
# Sorting an array
sorted_numbers = numbers.sort
puts sorted_numbers.inspect # => [1, 2, 3, 4, 5]
# Joining array elements into a string
joined_string = numbers.join(', ')
puts joined_string # => 1, 2, 3, 4, 5
Range
It represents a range of values.
age_range = 20..30
Ranges come with a set of useful operations as well.
# Creating a range
numeric_range = 1..5
puts numeric_range.to_a.inspect # => [1, 2, 3, 4, 5]
# Converting a range to an array
range_array = (1..3).to_a
puts range_array.inspect # => [1, 2, 3]
# Inclusive range (includes both 1 and 5)
inclusive_range = 1..5
puts inclusive_range.to_a.inspect # => [1, 2, 3, 4, 5]
# Exclusive range (excludes 5)
exclusive_range = 1...5
puts exclusive_range.to_a.inspect # => [1, 2, 3, 4]
# Checking if a value is within a range
puts numeric_range.include?(3) # => true
puts numeric_range.include?(8) # => false
# Checking if a value is at the beginning or end of a range
puts numeric_range.begin # => 1
puts numeric_range.end # => 5
# Step value in a range
stepped_range = 1..10
stepped_range_step_2 = stepped_range.step(2)
puts stepped_range_step_2.to_a.inspect # => [1, 3, 5, 7, 9]
Hash
It represents a collection of key-value pairs. Here are some common hash operations of Hashes:
# Creating a hash
person = { "name" => "John", "age" => 30, "city" => "New York" }
# Accessing values using keys
puts person["name"] # => John
puts person["age"] # => 30
# Adding a new key-value pair
person["occupation"] = "Engineer"
puts person.inspect
# => {"name"=>"John", "age"=>30, "city"=>"New York", "occupation"=>"Engineer"}
# Updating a value for an existing key
person["age"] = 31
puts person.inspect
# => {"name"=>"John", "age"=>31, "city"=>"New York", "occupation"=>"Engineer"}
# Removing a key-value pair
person.delete("city")
puts person.inspect
# => {"name"=>"John", "age"=>31, "occupation"=>"Engineer"}
# Checking if a key exists
puts person.key?("name") # => true
puts person.key?("gender") # => false
# Getting all keys or values
keys = person.keys
values = person.values
puts keys.inspect # => ["name", "age", "occupation"]
puts values.inspect # => ["John", 31, "Engineer"]
# Iterating over key-value pairs
person.each do |key, value|
puts "#{key}: #{value}"
end
# Output:
# name: John
# age: 31
# occupation: Engineer
# Checking if a hash is empty
puts person.empty? # => false
# Clearing all key-value pairs in a hash
person.clear
puts person.inspect # => {}
Regexp
It represents a pattern used for string matching.
pattern = /pattern/
Here are some common regular expression operations in Ruby:
# Matching a pattern
pattern = /world/
result = "hello world" =~ pattern
puts result # => 6 (index where the pattern starts)
# Checking if a pattern exists in a string
contains_pattern = "hello world" =~ /world/
puts contains_pattern.nil? ? "Not found" : "Found" # => Found
# Matching multiple occurrences of a pattern
matches = "hello world and world again".scan(/world/)
puts matches.inspect # => ["world", "world"]
# Case-insensitive matching
case_insensitive_match = "Hello World" =~ /world/i
puts case_insensitive_match.nil? ? "Not found" : "Found" # => Found
# Capturing groups
text = "Lite Rank"
match = text.match(/(\w+) (\w+)/)
puts match[0] # => John Doe (entire match)
puts match[1] # => John (first captured group)
puts match[2] # => Doe (second captured group)
# Substitution
new_text = "Hello, Alice!".gsub(/Alice/, "Bob")
puts new_text # => Hello, Bob!
# Anchors (^ and $) for matching start and end of a line
starts_with_hello = "hello world" =~ /^hello/
puts starts_with_hello.nil? ? "Not found" : "Found" # => Found
ends_with_world = "hello world" =~ /world$/
puts ends_with_world.nil? ? "Not found" : "Found" # => Found
Set
A Set
is a collection of unordered, unique elements.
require 'set'
my_set = Set.new([1, 2, 3, 4, 5])
puts my_set # => #<Set: {1, 2, 3, 4, 5}>
Code Challenge
Take a sentence as input and output a hash where the keys are unique words in the sentence, and the values are the frequencies of each word.
Should output:
{"the"=>2, "quick"=>1, "brown"=>1, "fox"=>1, "jumps"=>1, "over"=>1, "lazy"=>1, "dog"=>1}
.