Skip to content

Instantly share code, notes, and snippets.

@jonny-gates
Created July 10, 2019 09:35
Show Gist options
  • Save jonny-gates/14aacb9a952d75fb52f0eb25214ead50 to your computer and use it in GitHub Desktop.
Save jonny-gates/14aacb9a952d75fb52f0eb25214ead50 to your computer and use it in GitHub Desktop.
Exercises from Flow & Arrays lecture
# Define an array
beatles = ["john", "ringo", "seb"]
# 0 1 2
# Read an element
beatles[1]
# Modify an element
beatles[2] = "george"
# Create an element
beatles << "paul"
beatles.push("paul")
# Delete
beatles.delete("paul")
beatles.delete_at(1)
# Create: << / push
# Read: [index]
# Update: [index] =
# Delete: delete/ delete_at
beatles.each do |beatle|
puts "#{beatle.capitalize} is a Beatle!"
end
beatles << 3
joined_beatles = beatles.join(":") # returns a string
joined_beatles.split(":") # returns an array
beatles.length # /count/size
puts "heads or tails?"
puts ">"
player_choice = gets.chomp
computer_choice = ["heads", "tails"].sample
# if player_choice == computer_choice
# result = "win"
# else
# result = "lose"
# end
# condition ? code_if_truthy : code_if_falsy
result = player_choice == computer_choice ? "win" : "lose"
puts "You #{result}, the coin was #{computer_choice}"
puts "What do you want to do? [read|write|exit]"
puts ">"
choice = gets.chomp
# if choice == "write"
# puts "Entering write mode"
# elsif choice == "read"
# puts "Entering read mode"
# elsif choice == "exit"
# puts "Bye bye!"
# else
# puts "wrong choice!"
# end
case choice
when "write" then puts "Entering write mode"
when "read" then puts "Entering read mode"
when "exit" then puts "Bye bye!"
else
puts "wrong choice!"
end
price = rand(5) # 0 and 4
guess = nil
until price == guess
puts "Guess the price"
guess = gets.chomp.to_i
end
puts "You won! The price was £#{price}"
# hour = Time.now.hour
puts "what's the time"
hour =gets.chomp.to_i
is_morning = (hour >= 9 && hour < 12)
is_afternoon = (hour > 14 && hour < 16)
if is_morning || is_afternoon
puts "Shop is open!"
else
puts "Shop is closed!"
end
puts "What's the time? (hour)"
puts ">"
hour = gets.chomp.to_i
if hour < 12
puts "Good morning!"
elsif hour > 18
puts "Good evening - pub time!"
elsif hour > 12
puts "Good afternoon"
else
puts "Lunch time!"
end
# more specific conditions go higher!
puts "How old are you?"
puts ">"
age = gets.chomp.to_i
condition = (age >= 18)
if condition
puts "You can vote!"
else
puts "You can't vote"
end
# puts "You can vote!" unless !condition
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment