View procs_study.rb
# Procs are just closures:
def my_method_1
counter = 0 # => 0
proc { counter += 1 } # => #<Proc:0x007fadc9244ec8@/Users/durrellchamorro/code/scratch.rb:4>
end # => :my_method_1
my_proc = my_method_1 # => #<Proc:0x007fadc9244ec8@/Users/durrellchamorro/code/scratch.rb:4>
my_proc.call # => 1
my_proc.call # => 2
View perfect_numbers.rb
require 'prime'
module PerfectNumber
def self.classify(number)
raise "Number must be greater than or equal to two" if number < 2
aliquot_sum = generate_aliquot_sum(number)
return 'deficient' if aliquot_sum < number
return 'abundant' if aliquot_sum > number
'perfect'
View perfect_numbers.rb
require 'benchmark'
class PerfectNumber
def self.classify(number)
raise RuntimeError if number <= 1
sum_of_divisors = add_divisors(number)
return 'deficient' if sum_of_divisors < number
return 'abundant' if sum_of_divisors > number
'perfect'
View word_count.rb
class Phrase
def initialize(words)
@words = words
end
def word_count
count = Hash.new(0)
@words.scan(/\b[\w']+\b/) do |word|
count[word.downcase] += 1
View crypto_square.rb
class Crypto
def initialize(text)
@text = text
end
def normalize_plaintext
@text.gsub(/\W/,'').downcase
end
def size
View anagram.rb
class Anagram
def initialize(word)
@actual_word = word
@sorted_word = sort word
end
def match(list)
selected = list.select { |word| sort(word) == @sorted_word }
selected.delete_if { |word| word.downcase == @actual_word }
end
View wordy.rb
class WordProblem
def initialize(string)
@problem = string
end
def answer
operations = extract_operations @problem
fail ArgumentError, 'Valid operations: plus, minus, multiplied or divided' if operations.empty?
numbers = extract_numbers @problem
index = 0
View sum.rb
class SumOfMultiples
def initialize(*numbers)
@numbers = numbers
end
def self.to(limit)
new(3, 5).to(limit)
end
def to(limit)
View nth_prime.rb
class Prime
def self.nth(nth_prime)
raise ArgumentError if nth_prime == 0
return 2 if nth_prime == 1
primes = [2,3]
5.step(by:2) do |potential_prime|
break if primes.size == nth_prime
primes << potential_prime if prime? potential_prime
end
View saddle_points.rb
class Matrix
def initialize(raw_data_string)
@data = raw_data_string
end
def rows
format @data
end
def columns