Skip to content

Instantly share code, notes, and snippets.

def game
# create an array [rock, paper, scissors]
options = ["rock", "paper", "scissors"]
# create a random input
computer_input = options.sample
puts "Rock, paper, scissors?"
player_input = gets.chomp.downcase
# create player's input
def game_refacto
game_logic = { 'rock' => 'scissors', 'paper' => 'rock', 'scissors' => 'paper' }
options = game_logic.keys
computer_input = options.sample
puts "#{options.join(', ')}?"
player_input = gets.chomp.downcase
win = "You win! Computer input was #{computer_input}"
lose = "You lose! Computer input was #{computer_input}"
def acronymise(string)
# look for first letter in each word
# concatenate in a string
# upcase
# return value
acronym = ""
string.split(" ").each do |word|
acronym += word[0].upcase
end
return acronym
musicians = [
'Jimmy Page',
'Robert Plant',
'John Paul Jones',
'John Bonham'
]
# SELECT
begins_with_r = musicians.select { |musician| musician.start_with?("R") }
def something_slow
time = Time.now
puts "I am doing something slow"
yield
puts "Elapsed time : #{Time.now - time}"
end
something_slow { sleep(2) }
something_slow { sleep(1) }
def beautify_name(first_name, last_name)
full_name = "#{first_name.capitalize} #{last_name.upcase}"
yield(full_name)
end
message = beautify_name("john", "lennon") do |full_name|
"Greetings #{full_name}, you look quite fine today!"
end
puts message # => "Greetings John LENNON, you look quite fine today!"
def encrypt(text)
alphabet = ("A".."Z").to_a
text.split(' ').map do |word|
word.split('').map do |letter|
position = alphabet.index(letter)
new_position = position - 3
alphabet[new_position]
end.join('')
end.join(' ')
def better_acronymise(string)
return string.split.map { |word| word[0].upcase}.join
end
p better_acronymise("Frequently Asked Question")
puts better_acronymise("Frequently Asked Question") == "FAQ"
p better_acronymise("Bois d'Arcy")
puts better_acronymise("Bois d'Arcy") == "BD"
p better_acronymise(" Hello World ")
puts better_acronymise(" Hello World ") == "HW"
class Building
attr_reader :width, :length
attr_accessor :name
def initialize(name, width, length)
@name = name
@width = width
@length = length
end
class Butler
attr_reader :name, :associated_house
def initialize(name, associated_house)
@name = name
@associated_house = associated_house
end
def clean_associated_house
puts "#{associated_house.name} cleaned by #{name} !"