Skip to content

Instantly share code, notes, and snippets.

@ogryzek
Last active April 25, 2016 19:12
Show Gist options
  • Select an option

  • Save ogryzek/9612639 to your computer and use it in GitHub Desktop.

Select an option

Save ogryzek/9612639 to your computer and use it in GitHub Desktop.

Week 1: Homework

Ruby Basics

1.) Ask user for a number then print out the number multiplied by 5 and then the same number added to itself

# Ask user for a number then print out the number multiplied by 5 and then the same number added to itself
puts "enter a num"
answer = gets.chomp.to_i
puts "The number: #{answer} The number multiplied by 5: #{(answer*5)+answer}"

Ruby Numbers

1.) Find out how to get the Sine and Cosine of a give number in Ruby

# Find out how to get the Sine and Cosine of a give number in Ruby
Math::sin(x) #Math.sin(x)
Math::cos(x) #Math.cos(x)

2.) Find out how to get the PI in Ruby and then write a formula using that to convert degrees to radians

200 * (Math::PI / 180)
# Find out how to get the PI in Ruby and then write a formula using that to convert degrees to radians

Strings

1.) Given a string my_string = "Hello World" Find out a way to get a substring that contains the last 4 characters.

# Given a string
# my_string = "Hello World" 
# Find out a way to get a substring that contains the last 4 characters.
my_string = "Hello World"
sub_string = my_string[-4,4] # my_string[-4..-1]

2.) Take a string a find a way to display each character on a new line with its case swapped so if I give: Hello I will get:
h
E
L
L
O

# Take a string a find a way to display each character on a new line with its case swapped so if I give: Hello I will get:  
# h  
# E  
# L  
# L  
# O  
puts "Hello".swapcase.chars

3.) Find a way that will return the letter that occurred most in a given string. For instance if you give it: Hello it will give back the letter: l

# Find a way that will return the letter that occurred most in a given string. For instance if you give it: Hello it will give back the letter: l
string = "Aaap noot mies".downcase

chars = Hash.new(0)

string.each_char do |s|
	chars[s] += 1
end

puts chars.max_by{|k, v| v}[0][0]

Control Flow

1.) Write a code that will check if a given variables a is greater than 10 then it will print "Hello World". If it's greater than 100 it will print "Hello Universe". Otherwise it will do nothing.

puts "Please enter a number: "
num = gets.chomp

if num.to_i > 1000
puts "Hello UNIVERSE!" 
elsif num.to_i > 100
puts "Hello world!" 
end
# Write a code that will check if a given variables a is greater than 10 then it will print "Hello World". If it's greater than 100 it will print "Hello Universe". Otherwise it will do nothing.  

2.) Write a code that print "what year was you can made in"? and then you should print "Future Car", "New Car", "Old Car", "Very Old Car", "Ancient Car" based on the year entered from the user. You can use dates of your choice to determine the state of the car.

# Write a code that print "what year was you can made in"? and then you should print "Future Car", "New Car", "Old Car", "Very Old Car", "Ancient Car" based on the year entered from the user. You can use dates of your choice to determine the state of the car.
print "What year was your car made in: "
car_year = gets.chomp.to_i
if car_year > 2014
    puts "Future Car!"
elsif car_year == 2014
    puts "New Car!"
elsif car_year > 2000
    puts "Old Car!"
elsif car_year > 1990
    puts "Very Old Car!"
else
    puts "Ancient Car!"
end

3.) Write a code that takes a number and then prints the power of three to that number if it's divisible by three and it print the power of two if it's divisible by 2 and prints the number itself otherwise.

# Write a code that takes a number and then prints the power of three to that number if it's divisible by three and it print the power of two if it's divisible by 2 and prints the number itself otherwise.
puts "Please enter a number:"
num = gets.chomp.to_i

if num % 3 == 0
puts num ** 3
elsif num % 2 == 0
puts num ** 2
else
puts num
end

4.) Write a code that takes user's input and then prints out "Yes it has C" if entered input contains the letter "C" (upper or lower case). And it prints "There is no C" if it doesn't.

# Write a code that takes user's input and then prints out "Yes it has C" if entered input contains the letter "C" (upper or lower case). And it prints "There is no C" if it doesn't.  
print "Please enter a sentence: "
string = gets.chomp.downcase
if string.slice("c") == nil
  puts "Doesn't include C!"
else
  puts "It has C!"
end

5.) Using case / when statements ask user to enter the coffee shop they want to order from and then print: "Grande Latte" if they enter Starbucks and "Double Double" if they enter "Tim Hortons" and "Medium Coffee" if they enter Blenz and "I don't know this shop" if the enter something else.

# Using case / when statements ask user to enter the coffee shop they want to order from and then print: "Grande Latte" if they enter Starbucks and "Double Double" if they enter "Tim Hortons" and "Medium Coffee" if they enter Blenz and "I don't know this shop" if the enter something else.
puts "What would you like to order Starbucks, Tim Hortons or Blenz?"
order = gets.chomp.downcase

case order
when "starbucks" then puts "Grande Latte"
when "tim hortons" then puts "Double Double"
when "blenz" then puts "Medium Coffee"
else puts "I don't know this shop"
end

Loops

1.) Use while loop to print 1 to 15 (both numbers included)

# Use while loop to print 1 to 15 (both numbers included)
x = 1
while x <= 15
puts x
x += 1
end

2.) Use until loop to print 5 to 15 (both numbers included)

# Use until loop to print 5 to 15 (both numbers included)
i = 5

until i == 16
puts "#{i}"

i += 1
end

3.) Print 10 to 20 using for loop in two ways:

  • using range with three dots
  • using range with two dots
# Print 10 to 20 using for loop in two ways:
#   * using range with three dots
#   * using range with two dots
for x in 10..20
puts x
end

for x in 10...21
puts x
end

4.) Write the numbers from 15 to 50 using upto. Write the letters from "O" to "B" using downto

# Write the numbers from 15 to 50 using upto. 
counter = 5
until counter > 15
  print "#{counter}"
  counter += 1
end

5.) Write the letters from "O" to "B" using downto

# Write the letters from "O" to "B" using downto
79.downto(66) {|x| puts x.chr}

5.) *** Challenge***: Write a method that takes a number N and then draw a triangle that has N number of letter O on each of its sides.

# Write a method that takes a number N and then draw a triangle that has N number of 
# letter O on each of its sides. For example given the number 5 your will get 
# something like:
#     O
#    O O
#   O O O
#  O O O O
# O O O O O
puts "Please enter a number"

user_num = gets.chomp.to_i

i = 0
x = user_num
while i <= user_num
  x.times { print " " }
  i.times { print "O "}
  puts ""
  x -= 1
  i = i+1
end

Arrays

1.) Keep asking user for input and add their input to an array until they type "exit". * After that print out the number of input they've entered. For example print: * You've entered 10 inputs

# Keep asking user for input and add their input to an array until they type "exit". 
# After that print out the number of input they've entered. For example print:
# You've entered 10 inputs
array = []
puts "Please enter or type exit to exit: "
string = gets.chomp.downcase
while string != "exit"
array << string
puts "Please enter or type exit to exit: "
string = gets.chomp.downcase
end
puts "You've entered #{array.count} inputs!"

2.) Reverse engineer the "reverse" method in Arrays which reverses the order of the array. Bonus: Try doing it using another way.

# Reverse engineer the "reverse" method in Arrays which 
# reverses the order of the array. ***Bonus***: 
# Try doing it using another way.  
my_string = "This is a string"
 
my_array =  my_string.scan(/\w+/) 
 
count = my_array.count
 
for x in 1..my_array.count
  puts my_array[count-1]
  count -=1
end

3.) Given an array of words. Return back an array of numbers that contains the length of each word in the first array in the same order.

# Given an array of words. Return back an array of numbers that 
# contains the length of each word in the first array in the same order.
def number_of_letters(words=["one", "two", "three", "four", "five"])
  arr = []
  words.each do |x|
    arr << x.length
  end
  arr
end

4.) Given a number N from the user. Generate an array that contains the first N numbers of the fibonacci sequence.

# Given a number N from the user. Generate an array that 
# contains the first N numbers of the fibonacci sequence.
puts "How many times?"
x = gets.chomp.to_i

fibonacci = []

x.times do
if fibonacci.size == 0 || fibonacci.size == 1
fibonacci << 1
else
fibonacci << fibonacci[-2] + fibonacci[-1]
end
end

print fibonacci

5.) Challenge: Write a method that takes a string as a sentence and returns the sentence reversed (consider words are separated by one or more spaces).

# Write a method that takes a string as a sentence and returns the
# sentence reversed (consider words are separated by one or more spaces).

6.) Challenge: Write a method that checks whether a passed String is a palindrome or not. A palindrome is a string that reads that same both ways for instance: sugnangus

# Write a method that checks whether a passed String is a palindrome or not. 
# A palindrome is a string that reads that same both ways for instance: sugnangus

Hashes

1.) Write a code that will prompts a user to enter a sentence and then prints out a hash whose keys are the letter and values are the number of occurrences of that letter, for example if use enters "hello world" will generate: {"h" => 1, "e" => 1, "l" => 3, "o" => 2, "w" => 1, "d" => 1}

#Write a code that will prompts a user to enter a sentence and then prints out a 
# hash whose keys are the letter and values are the number of occurrences of that 
# letter, for example if use enters "hello world" will generate:
# {"h" => 1, "e" => 1, "l" => 3, "o" => 2, "w" => 1, "d" => 1}
 def number_of_letters(words=["Orange", "Yellow", "Blue", "Red"])
    arr = []
    words.each do |x|
      arr <<  x.length
    end
   arr
 end

2.) Given a hash: {:a => "123", :b => "345", :c => "678", :d => "910"} Write code that generates an array that combines the keys and values:
so the resulting array should be: ["a123", "b345", "c678", "d910"]

# Given a hash:
# {:a => "123", :b => "345", :c => "678", :d => "910"}
# Write code that generates an array that combines the keys and values:
# so the resulting array should be:
# ["a123", "b345", "c678", "d910"]

my_hash = {:a => "123", :b => "345", :c => "678", :d => "910"}
my_array=[]
count = 0
 
my_hash.each do |key,value|
  s1 = key.to_s
  s2 = value
  s3 = s1 + s2
  my_array[count]=s3
  count +=1
end
puts my_array

3.) Write some code that keeps asking use for book names until the user enters "exit". After typing exit the program should display all the entered book names sorted.

# Write some code that keeps asking use for book names until the user 
# enters "exit". After typing exit the program should display all the 
# entered book names sorted.

puts "Please enter books you owned or press exit: "
book_name = gets.chomp.capitalize
array = []
until book_name == "Exit"
    array << book_name
    book_name = gets.chomp.capitalize
end
puts array.sort

4.) Given the following hash...

bc_cities_population = {
  vancouver: 2135201, 
  victoria:  316327, 
  abbotsford: 149855, 
  kelowna: 141767, 
  nanaimo:  88799, 
  white_rock: 82368, 
  kamloops: 73472, 
  chilliwack: 66382 
 }

Write a method that takes the hash and prints if city is large (more than 100,000) or small (otherwise). Printing something like: "Vancouver is a large city"

#bc_cities_population = {vancouver: 2135201, victoria:  316327, abbotsford: 149855, kelowna: 141767, nanaimo:  88799, white_rock: 82368, kamloops: 73472, chilliwack: 66382 }  
#Write a method that takes the hash and prints if city is large 
# (more than 100,000) or small (otherwise). Printing something 
# like: "Vancouver is a large city"  

bc_cities_population = {:vancouver => 2135201,
  :victoria => 316327,
  :abbotsford => 149855,
  :kelowna => 141767,
  :nanaimo =>  88799,
  :white_rock => 82368,
  :kamloops => 73472,
  :chilliwack => 66382
}


def city_size(cities)

  cities.each do |city, pop|
    city = city.to_s.gsub(/_/, " ")
    if pop > 100_000
      puts "#{city.capitalize} is a large city."
    else
      puts "#{city.capitalize} is a small city."
    end
  end
end

city_size(bc_cities_population)

5.) Ask the user for personal information: first name, last name, city of birth and age. Then store than information in a hash. After that loop through the hash and display the results, for example:

  • Your first name is Tam.
  • Capitalize the inputs from the user if they are capitalizable
# Ask the user for personal information: 
# first name, last name, city of birth and age. 
#
# Then store that information in a hash. 
# After that loop through the hash and display the results, for example:  
#  * Your first name is Tam.  
#  * Capitalize the inputs from the user if they are capitalizable  
puts "Please enter your first name:"
first_name = gets.chomp
 
puts "Please enter your last name:"
last_name = gets.chomp
 
puts "Please enter your city of birth:"
city = gets.chomp
 
puts "Please enter your age:"
age = gets.chomp
 
personal_info = {"first name" => first_name, "last name" => last_name, "city" => city, "age" => age}
 
personal_info.each do |key,value|
  if value.respond_to? (:capitalize)
    puts "Your #{key.to_s} is #{value.capitalize}"
  else
      puts "Your #{key.to_s} is #{value}"
  end
end

6.) Given the following hash...

bc_cities_population = {
	vancouver: 2135201, 
	victoria:  316327, 
	abbotsford: 149855, 
	kelowna: 141767, 
	nanaimo:  88799, 
	white_rock: 82368, 
	kamloops: 73472, 
	chilliwack: 66382 
	}

Write a method that takes the hash above and returns an array of the values divided by 1000 in one line of code

def divide_each_by(hash, val=1000.0)
  hash.each_value {|x| puts x.to_i/val }
end

7.) Given a hash of average temperatures:
average_temperature_in_c = {vancouver: 13.7, edmonton: 8.5, Calgary: 10.5}
Create another hash called average_temperature_in_f that has the same keys (city names) but the temperatures are in Fahrenheit instead of Celcius.

The formula to convert Celsius to Fahrenheit is: F = C * 9/5 + 32

average_temperature_in_c = {
  :vancouver => 13.7,
  :edmonton => 8.5,
  :Calgary  => 10.5
  }

average_temperature_in_f = {}

average_temperature_in_c.each do |city, temp|
  average_temperature_in_f[city] = temp * 9 / 5 + 32
end

average_temperature_in_f.each_pair {|k, v| puts "The average temperature in #{k} is #{v} F"}

8.) Ask the user for the following information: first name, last name and age
Then ask them for cities they've visited (they can keep entering until they type "done").
Store all the entered data in a hash and then loop through the hash and display results

hash_of_info = {}
hash_of_info[:city]=[]
i=0
 
puts "What is your first name?"
first_name = gets.chomp
hash_of_info[:firstname] = first_name
 
puts "What is your last name?"
last_name = gets.chomp
hash_of_info[:lastname] = last_name
 
puts "What is your age?"
age = gets.chomp
hash_of_info[:age] = age
 
puts "Name a city you have visitied:"
city = gets.chomp
hash_of_info[:city] << city
 
while city != "done"
  puts "Name a city you have visitied (or type 'done'):"
  city = gets.chomp
  hash_of_info[:city] << city if city != "done"
  i +=1
end
 
puts hash_of_info

9.) Reverse Engineering Hash's "keys" and "values" methods

hash = {'title1' => 'value1', 'title2' => 'value2'}

def values(x)
values = Array.new()
x.each { |key, value| values << value }
values
end

def keys(x)
keys = Array.new()
x.each { |key, value| keys << key }
keys
end

print keys(hash)
print values(hash)

10.) Challenge: You are given an array with numbers between 1 and 1,000,000. One integer is in the array twice. How can you determine which one? Can you think of a way to do it using little extra memory.
Bonus: Solve it in two ways: one using hashes and one without.

#the answer

Exceptions

1.) Create an Exception class called AwesomeException and make it inherit from StandardError

Raise an exception with the type you've created and rescue from it.

class AwesomeException < StandardError
def initialize(msg = "You've triggered Awesome Exception!")
   super(msg)
end
end


begin
raise AwesomeException
rescue => e #get the object form the external service
puts "#{e.message}"
end

Ruby - OOP

1.) Make two classes dog and bones. The dog class must have initialize method that takes dog's color and type. The bone must have an initialize method that assigns a size for the bone.

The dog class must have a give method that takes a bone object and add it it to an array of bones for the dog. The dog can take a maximum of three bones so if you give it more than three it will will print, I have too many bones.

The dog class must have a eat bone that when you call it it removes a bone from the array of bones and print "yummy! I ate 'big' bone" the 'big' part comes from the size attribute of bone.

# bone.rb
class Bone
  attr_accessor :size
  
  def initialize(size)
    @size = size
  end
end

# dog.rb
require './bone.rb'
 
class Dog
  def initialize(color, type)
    @color, @type = color, type
    @bones = []
  end
	
  def give_a_bone(bone)
    if @bones.length < 3
      @bones << bone
    else
      print "I have too many bones."	
    end
  end
 
  def eat_a_bone
    print "Yummy! I ate a #{@bones.last.size} bone"
    @bones.pop
  end
	
end

# givebone.rb
require './dog.rb'
require './bone.rb'
 
somedog = Dog.new('white','dumb Dog')
small_bone = Bone.new('small')
med_bone = Bone.new('medium')
l_bone = Bone.new('large')
 
puts somedog
 
puts small_bone
 
somedog.give_a_bone(small_bone)
somedog.give_a_bone(med_bone)
somedog.give_a_bone(l_bone)
somedog.give_a_bone(l_bone)
 
somedog.eat_a_bone()
somedog.eat_a_bone()
somedog.eat_a_bone()

2.) Build a class Phone that takes phone "brand" and "type" as parameters.

Add two methods: call

Add two private methods: connect to internet

class Phone

  def initialize( brand = "", type = "")
    @brand = brand
    @type = type
  end

  def call
    connect_internet
  end

  private

  def connect_internet
    puts "Connect #{@brand} to the internet"
  end
end

3.) Pick three objects from the room around you and model them in terms of classes.
* Make sure every class contains: * Public methods * Private methods * Attribute accessors

# smart_phone.rb
class SmartPhone
  attr_accessor :brand, :model
  
  def initialize(brand="", model="", amount=0)
    @brand, @model, @amount = brand,model,amount
  end
 
  def buy_phone
   quantity_change(1)
  end
 
  def sell_phone
    quantity_change(-1)
  end
 
  private
  def quantity_change(amount)
    @amount = @amount + amount
  end
end
 
# mac_book.rb
class MacBook
  attr_accessor :screen_size, :speed
 
  def macbook_method
    puts "macbook_method is public"
    private_macbook
  end
  
  private
  def private_macbook
    puts "private_method is private"
  end
end
 
# laptop.rb
class Laptop
  attr_accessor :brand, :model
 
  def latptop_method
    puts "laptop_method is public"
    laptop_private
  end
 
  private
  
  def laptop_private
    puts "laptop_private is private"
  end
end 

4.) Build a class called FizzBuzz that takes two numbers as parameters and then have a method called run that returns a fizzbuzz array (numbers from 1 to 100, numbers divisible by the first number replaced by 'fizz' and numbers replaced by the second number replaced by 'buzz' and numbers divisible by both replaced by 'fizzbuzz').
For instance this code should work with your class:

fb = FizzBuzz.new(3,5)
fb.run # returns an array like: [1, 2, 'fizz', 4, 'buzz, ...

Now modify your solution to make it flexible and be able to change the numbers after you create the object. For instance:

fb = FizzBuzz.new(3,5)
fb.run # returns an array: [1, 2, 'fizz', 4, 'buzz, ...
fb.first_number = 2
fb.second_number = 3
fb.run # returns an array: [1, 'fizz', 'buzz', 'fizz', 5, 'fizzbuzz'...

Answer

class Fb
  attr_accessor :num1, :num2
  
  def initialize(num1 = 3, num2 = 5)
    @num1, @num2 = num1, num2
  end
 
  def run
    fizzbuzz = []
 
    0..100.times do |n|
      fizzbuzz << 'fizzbuzz' if (n % @num1) +  (n % @num2) == 0
      fizzbuzz << 'fizz' if (n % @num2) == 0
      fizzbuzz << 'buzz' if (n % @num1) == 0
      fizzbuzz <<  n
      puts fizzbuzz
    end
  end	
end

5.) Build a class Animal that has two methods "eat" that prints "I'm eating" and a method "walk" that prints "I'm walking"

Now build a class called Dog that inherits from the Animal class. Add a new method to this class called bark that returns woof. Override the eat methods and make it print whatever the Animal class eat method prints and then print "bones are yummy"

Now build a class called Cat that inherits from the Animal class. Override the eat methods and make it print "I love Fish"

# animal.rb
class Animal

  def eat
    puts "I am eating"
  end

  def walk
    puts "I am walking"
  end
end

# dog.rb
class Dog < Animal

  def bark
    puts "woof"
  end

  def eat
    super
    puts "bones are yummy"
  end
end

# cat.rb
class Cat < Animal

  def eat
    puts "I love fish"
  end
end

6.) Model a blog post and comments with classes and make it so a blog has many comments.
Add the ability for me to add and remove comments from a blog.

# blog.rb
class Blog

  attr_accessor :comments

  def initialize
    @comments = Array.new
  end

  def post(comment)
    comments << comment
  end

  def read
    comments.each {|c| puts "Comment ##{(comments.index(c)+1)}: #{c.comment}" }
  end

  def delete(which)
    if which > comments.length  
      puts "That comment doesn't exists"
    else
      comments.delete_at((which-1))
    end
  end

end

# comment.rb
class Comment

  attr_accessor :comment

  def initialize(text)
      @comment = text
  end

end

7.) Challenge: Model all of your book library using classes.

Have the following in your library:

  • Different book types (paper, digital and audio)
  • Different storage media (Book shelf, Computer, iPad, Kindle)
  • The main library where it contains all the book with all the types
  • Ability sort the books (regardless of their type)

Bonus
Add the following features:

  • Ability to store in multiple media (for instance Kindle and Computer)
  • Ability to search a book by its name (or a portion of its name)
# answer...

8.) Challenge: Try to model a chess game using objects and classes model the pieces, the board, the players, the movements and provide ability to store state of board and ability to announce winner.

Bonus: Make it functional so that you:

  • Enforce the places that each piece can move
  • You can't move a piece outside the boundaries of the board
  • Enforces turns for players.

Modules & Mixins

1.) Create two classes named Box one inside a module called Mail and the other one inside a module called Storage.

module Mail
  class Box
  end
end
 
module Storage
  class Box
  end
end
 
class Mail::Box
end
 
class Storage::Box
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment