Skip to content

Instantly share code, notes, and snippets.

function fizzBuzz(max) {
for (var num=1; num <= max; num++) {
var current = "";
if (num % 3 == 0) {
current += "Fizz";
}
if (num % 5 == 0) {
current += "Buzz";
}
if (!(current)) {
def fizzbuzz(max)
(1..max).to_a.each do |num|
current = ""
current << "Fizz" if num % 3 == 0
current << "Buzz" if num % 5 == 0
current<< num.to_s if current.empty?
puts current
end
end
p Calculator.add(6, 5, 9) # => 20
p Calculator.multiply(2, 4) # => 8
p Calculator.tester(2, 3, 4) # => "Sorry, 'tester' method not avilable!"
p Calculator.median(1, 2, 3, 4) # => 2.5
p Calculator.median(1, 2, 3, 4, 5) # => 3
p Calculator.mode(2, 2, 2, 6, 5, 8, 8, 8, 8, 5) # => 8
p Calculator.mode(2, 2, 2, 2, 6, 5, 8, 8, 8, 8, 5) # => [2, 8]
module ExtraArrayMethods
def average(*nums)
nums.dup.inject(:+) / nums.length
end
def median(*nums)
nums = nums.uniq.sort
if nums.length < 4
return nums[0] if nums.length == 1
class Calculator
extend ExtraArrayMethods
def self.method_missing(method, *nums)
operators = {add: :+, subtract: :-, multiply: :*, divide: :/}
if operators.keys.include?(method)
nums.inject(operators[method])
else
"Sorry, '#{method.to_s}' method not available!"
end
my_library.suggest_a_book
# output:
# "Why not pick up JavaScript & JQuery?"
my_library.suggest_an_author
# output:
# "How about reading something by Rod Stephens?"
my_library.books.each{|book| puts "\"#{book.title}\", by #{book.author}"}
# output:
# "The Well Grounded Rubyist", by David A. Black
# "JavaScript & JQuery", by Jon Duckett
# "Essential Algorithms", by Rod Stephens
# "Clean Code", by Robert C. Martin
my_library.add_book("The Well Grounded Rubyist", "David A. Black")
my_library.add_book("JavaScript & JQuery", "Jon Duckett")
my_library.add_book("Essential Algorithms", "Rod Stephens")
my_library.add_book("Clean Code", "Robert C. Martin")
p my_library # output:
# #<Library:0x00000001296750 @books=[
# #<Book:0x00000001296610 @title="The Well Grounded Rubyist", @author="David A. Black">,
# #<Book:0x000000012964d0 @title="JavaScript & JQuery", @author="Jon Duckett">,
# #<Book:0x00000001296390 @title="Essential Algorithms", @author="Rod Stephens">,
my_library = Library.new
p my_library
# output: #<Library:0x00000001d468d0 @books=[]>
class Library
attr_accessor :books
def initialize
@books = []
end
def add_book(title, author)
@books << Book.new(title, author)
end