Last active
February 8, 2023 00:17
-
-
Save caioertai/9eadf0886021f6c23c74b025906457f6 to your computer and use it in GitHub Desktop.
Ruby Day 2 Livecode - Flow, Conditionals & Arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The one we built | |
def acronimyzer(sentence) | |
# Capitalize sentence | |
caps = sentence.upcase | |
# Split words | |
words = caps.split | |
# Pick first letter of each word | |
letters = [] | |
words.each do |word| | |
letters.push(word[0]) | |
end | |
# Return acronym | |
letters.join | |
end | |
# A one liner with a more powerful iterator: #map | |
# Explanation of the one line refactor: | |
# 1. split returns from the sentence an array of words (splits on " ", spaces) | |
# 2. map is a special iterator (more on this next lecture) that returns a | |
# changed array based on the value of its block's iterations | |
# We're taking each of the words, pick the first letter [0], and upcasing it | |
# 3. When the map block is closed we have an array of upcased first letters, like: | |
# ["F", "A", "Q"], so we just #join them again on a string "FAQ" to close the deal | |
def refactored_acronimyzer(sentence) | |
sentence.split.map { |word| word[0].upcase }.join | |
end | |
puts refactored_acronimyzer("Frequently Asked Questions") == "FAQ" | |
puts refactored_acronimyzer("oh my god") == "OMG" | |
puts refactored_acronimyzer("") == "" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Save the valid options in an array | |
OPTIONS_ARRAY = %w[Rock Paper Scissors] | |
# Asking Player option | |
puts "Choose your option [Rock, Paper, Scissors]" | |
player_option = gets.chomp.capitalize | |
# Check is the option is valid and keep ask if not | |
until OPTIONS_ARRAY.include?(player_option) | |
puts "[#{player_option}] is not a valid option" | |
puts "Choose your option [Rock, Paper, Scissors]" | |
player_option = gets.chomp.capitalize | |
end | |
# Selecting PC option | |
pc_option = OPTIONS_ARRAY.sample | |
# Comparing Player and PC options | |
if player_option == pc_option | |
puts "It Draw!, both you pick same same" | |
elsif player_option == "Rock" && pc_option == "Scissors" | |
puts "PC picked #{pc_option}. Player wins!" | |
elsif player_option == "Paper" && pc_option == "Rock" | |
puts "PC picked #{pc_option}. Player wins!" | |
elsif player_option == "Scissors" && pc_option == "Paper" | |
puts "PC picked #{pc_option}. Player wins!" | |
else | |
puts "PC picked #{pc_option}.PC wins!" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment