Skip to content

Instantly share code, notes, and snippets.

@pengjunp
pengjunp / max.rb
Last active April 26, 2016 19:33 — forked from davidvandusen/max.rb
maximum value
# Find the maximum
def maximum(arr)
result = nil
if !arr.is_a? (Array)
result = "not an array"
else
arr.each { |i| result = i if result == nil || i > result}
return result
end
end
@pengjunp
pengjunp / fizzbuzz-task1.rb
Last active April 26, 2016 19:29
FuzzBuzz Refactor
def fuzzbuzz (start_num, end_num)
start_num.upto(end_num) do |i|
if i % 5 == 0 && i % 3 == 0
puts "FizzBuzz"
elsif i % 5 == 0
puts "Buzz"
elsif i % 3 == 0
puts "Fizz"
else
puts i
@pengjunp
pengjunp / renter.rb
Created April 26, 2016 19:51
The Yuppie Vancouverite
# must be baller and either furnished or rent cheaper than 2100
# def rent?(furnished, rent, baller)
# if baller && (furnished || rent < 2100)
# return true
# else
# return false
# end
# end
@pengjunp
pengjunp / shakil.rb
Created April 26, 2016 21:44
Shakil the Dog
# Save this file to your computer so you can run it
# via the command line (Terminal) like so:
# $ ruby shakil_the_dog.rb
#
# Your method should wait for user input, which corresponds
# to you saying something to your dog (named Shakil).
# You'll probably want to write other methods, but this
# encapsulates the core dog logic
def shakil_the_dog
@pengjunp
pengjunp / sort.rb
Last active April 27, 2016 05:51 — forked from davidvandusen/sort.rb
require 'benchmark'
# Sort the array from lowest to highest
def sort(arr)
swap = true
# Merge sort
while swap
swap = false
for i in 0..arr.length - 1
if i <= arr.length - 2 && arr[i] > arr[i + 1]
greater = arr[i]

Pry Cheat Sheet

Command Line

  • pry -r ./config/app_init_file.rb - load your app into a pry session (look at the file loaded by config.ru)
  • pry -r ./config/environment.rb - load your rails into a pry session

Debugger

def sign_price
# declare the total price
total = 0
# calculate the size
puts "Sign dimensions? length, width (feet)"
dimensions = gets.chomp.split(',', 2)
size = dimensions[0].to_f * dimensions[1].to_f
total += 15 * size
# calculate the colors
puts "How many colors?"
def count_letters (s)
result = Hash.new(0)
s.gsub(/\s/, "").each_char {|c| result[c] += 1}
puts result.inspect
end
count_letters("This is a random string that doesn't make any sense at all")
def letter_indices (s)
result = {}
@pengjunp
pengjunp / ex1.rb
Created May 2, 2016 20:11
I/O exercises
require 'rubygems'
require 'rest-client'
wiki_url = "http://en.wikipedia.org/"
wiki_local_filename = "wiki-page.html"
File.open(wiki_local_filename, "w") do |file|
file.write(RestClient.get(wiki_url))
end
module Flight
def Flight.fly(animal)
if animal.superclass.name == "Bird" || name = animal.name == "Bat"
"I'm a #{animal.name}, I'm flying!"
end
end
end