Skip to content

Instantly share code, notes, and snippets.

@caioertai
Created January 24, 2019 12:51
Show Gist options
  • Save caioertai/9fcecf99650ce41b403f9fb124c0c30a to your computer and use it in GitHub Desktop.
Save caioertai/9fcecf99650ce41b403f9fb124c0c30a to your computer and use it in GitHub Desktop.
# CRUD
musicians = [
'Arjen Lucassen',
'James LaBrie',
'Steven Wilson',
'Jeff Wayne'
]
# Create
musicians << 'John Lennon'
# Read
musicians[0] # => Arjen Lucassen
# Update
musicians[2] = 'Ringo'
# Destroy
musicians.delete('Ringo')
musicians.delete_at(2)
def greet(first_name, last_name)
full_name = "#{first_name.capitalize} #{last_name.upcase}"
yield(full_name)
end
greet_in_english = greet('john', 'lennon') do |name|
"Hello, #{name}"
end
puts greet_in_english
greet_in_portuguese = greet('john', 'lennon') do |name|
"E aí, #{name}?"
end
puts greet_in_portuguese
sing_gilberto_gil = greet('john', 'lennon') do |name|
"Alô alô, #{name}. Aquele abraço!"
end
puts sing_gilberto_gil
musicians = [
'Arjen Lucassen',
'James LaBrie',
'Steven Wilson',
'Jeff Wayne'
]
# Print all musicians name's using for
# for
for name in musicians
puts name
end
# Print all musicians name with for by using their index
# for
for i in 0...musicians.length
puts musicians[i]
end
# Print list of the musicians with their position in the list
# #each_with_index
musicians.each_with_index do |musician, index|
puts "#{index + 1}. #{musician}"
end
# Print all musicians names using #each
# #each
musicians.each do |musician|
puts musician
end
# Create an array of musicians names upcased
# #map
musicians_upcased = musicians.map do |musician|
musician.upcase
end
puts musicians_upcased
# Create an array with the first name of the musicians
# #map
musicians_first_name = musicians.map do |musician|
musician.split.first
end
# Count the musicians that start with J
# #count
number_of_musicians_starting_with_j = musicians.count do |musician|
musician.start_with?('J')
end
puts number_of_musicians_starting_with_j
# Extract the musicians that start with J
# #select
musicians_starting_with_j = musicians.select do |musician|
musician.start_with?('J')
end
puts musicians_starting_with_j
# Extract the musicians that don't start with J
# #reject
musicians_not_starting_with_j = musicians.reject do |musician|
musician.start_with?('J')
end
puts musicians_not_starting_with_j
def timer
start_time = Time.now
yield
end_time = Time.now
puts end_time - start_time
end
timer() do
puts 'Counting even numbers'
(0..10_000_000).count { |i| i.even? }
puts 'Finished counting '
end
timer() do
puts 'Waiting 1 second'
sleep 1
puts 'Finished waiting '
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment