Skip to content

Instantly share code, notes, and snippets.

@patriques82
Last active December 16, 2015 09:29
Show Gist options
  • Save patriques82/5413704 to your computer and use it in GitHub Desktop.
Save patriques82/5413704 to your computer and use it in GitHub Desktop.
Chapter 3 (Ruby)
#Project 4 (this one is credited to https://gist.github.com/tomtung/1973534)
class Class
def attr_accessor_with_history(attr_name)
attr_name = attr_name.to_s
attr_reader attr_name
attr_reader attr_name+"_history"
class_eval %Q{
def #{attr_name}=(value)
if(!defined?(@#{attr_name}_history))
@#{attr_name}_history = [@#{attr_name}]
end
@#{attr_name} = value
@#{attr_name}_history << value
end
}
end
end
#Project 5
module Enumerable
def each_with_custom_index(start, step)
self.each_with_index do |elt, index|
yield elt, index*step+start
end
end
end
#Project 6
class FibSequence
include Enumerable
@fibs=0
def initialize(nr)
@fibs=nr
end
def each
@prev=0
@index=0
@fibs.times do
if @index == 0
yield @index=1
else
temp=@index
yield @index=@prev+temp
@prev=temp
end
end
end
end
#Project 9
def each_with_flattening
self.each do |item|
if item.class == Array
item.each_with_flattening { |s| yield s }
else
yield item
end
end
end
#Project 10
module Enumerable
def each_permuted
arr_cpy = self.dup
if self.respond_to?(:each)
arr_cpy.sort_by { rand }
end
end
end
#Project 11 #Not quite sure if it works (inspired by http://stackoverflow.com/questions/12205180/implementing-binary-tree-in-ruby)
class BinaryTree
attr_accessor :val
def initialize(val=nil)
@val = val
@left = @right = nil
end
def empty?
@val == nil
end
def << (x)
if self.empty?
@val=x
else
test = @val <=> x
case test
when 1 # @val is greater
@left = BinaryTree.new(nil)
@left << x
when -1, 0 # @val is less or equal
@right = BinaryTree.new(nil)
@right << x
end
end
end
def each
unless self.empty?
@left.each { |val| yield val }
yield @val
@right.each { |val| yield val }
end
end
end
#Project 13
class Numeric
def dollars
Float.new(self)
end
def euro
self/1.3
end
def yen
self*0.012
end
def in(val)
case val
when :dollars
self
when :euro
self*1.3
when :yen
self/0.012
else
"not defined currency"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment