Skip to content

Instantly share code, notes, and snippets.

@barangerbenjamin
Created October 10, 2019 09:58
Show Gist options
  • Save barangerbenjamin/2c602d078152e40cce1c19c1a745e9d4 to your computer and use it in GitHub Desktop.
Save barangerbenjamin/2c602d078152e40cce1c19c1a745e9d4 to your computer and use it in GitHub Desktop.
my_array = ["Ben", "Phelim", "Arthur"]
# indexes 0 1 2
my_array.length # return the number of element in the array
# CRUD
# Read
my_array[0] # first element of array
my_array.first
my_array[-1]
my_array.last
# Create
my_array.push("Lucien") # same as => my_array << "Lucien"
# Update
my_array[0] = "Alex" # Reassign the value at index 0
# Delete
my_array.pop # delete last element of the array
my_array.delete("Lucien") # delete all element having the value of "Lucien"
my_array.delete_at(-1) # Delete element at index -1
my_array = ["Ben", "Phelim", "Arthur", "Alex"]
# Each - returns the original array
my_array.each do |name|
puts name
end
# Each with index - returns the original array
my_array.each_with_index do |name, index|
puts "#{index + 1} - #{name}"
end
# Map - returns a copy of the original array with element transformed
new_array = my_array.map do |name|
name.upcase
end
# Count - returns an integer. counter is incremented if the condition is true
number = my_array.count do |name|
name.start_with?("A")
end
# Select - returns an array with element matching the condition
starts_with_a = my_array.select do |name|
name.start_with?("R")
end
# Reject - returns an array without element matching the condition
starts_with_a = my_array.reject do |name|
name.start_with?("A")
end
# define a method timer
def timer
start_time = Time.now
yield # calls the block passed as an argument during the method call
puts "Elapsed time: #{Time.now - start_time}s"
end
# method called with a block
timer do
puts "starting task 1"
sleep(2)
puts "task 1 done!"
end
# method called with a block
timer do
puts "starting task 1"
sleep(1)
puts "task 1 done!"
end
# def a method taking 2 parameters
def greet(first_name, last_name)
full_name = "#{first_name.capitalize} #{last_name.upcase}"
yield(full_name) # Calls the block passed as an argument during the method call
end
# method called with a block
greet('john', 'lennon') do |full_name|
puts "Greetings #{full_name}, you look quite fine today!"
end
# method called with a block
greet('john', 'lennon') do |name|
puts "Bonjour #{name}, comment ça va ?!"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment