Skip to content

Instantly share code, notes, and snippets.

class Array
def new_count
self.inject(0) { |accum , i| yield(i) ? accum += 1 : accum }
end
end
# Exercise for the reader: Figure out why my original idea: "self.inject(0) { |accum , i| accum += 1 if yield(i) }" is not completely valid
class Array
def new_each
0.upto(self.length-1) do |index|
yield(self[index])
end
end
end
class Array
def new_collect
ar = []
self.each do |i|
ar << yield(i)
end
ar
end
end
class Book
attr_reader :title
def initialize()
@title = ""
end
def title=(str)
accum = []
str.split.each_with_index do |word, indx|
class RPNCalculator
def initialize()
@num_store = []
end
def push(n)
@num_store << n
end
class Dictionary
attr_accessor :entries, :keywords
def initialize()
@entries = {}
@keywords = []
end
def add(input)
if input.is_a?(String)
str = input
class Die
attr_accessor :sides
def initialize(sides)
@sides = sides
end
def roll
rand(sides) + 1
end
end
class Rectangle
def initialize(length, width)
@length = length
@width = width
end
def perimeter
(@length + @width) * 2
end
module InWords
def in_words()
if self == 0
return "zero"
end
lvl_array = %w{ not_called thousand million billion trillion }
max_lvl = (self.to_s.length - 1) / 3
n = self
class Numeric
def factorial()
self < 0 ? raise("You can't take the factorial of a negative number") : factorial_h(1,self)
end
def factorial_h(accum, n)
n <= 1 ? accum : factorial_h(accum * n, n -1 )
end
end