Skip to content

Instantly share code, notes, and snippets.

View jhamon's full-sized avatar

Jennifer Hamon jhamon

View GitHub Profile
@jhamon
jhamon / piece.rb
Last active December 23, 2015 21:19
class Piece
attr_reader :color
attr_accessor :pos
def initialize(color, pos)
@color = color # :white or :black
@pos = pos # position = [x, y]
end
def dup
class TreeNode
# ...
def dfs(target_value = nil, &blk)
# Depth-first search. Returns TreeNode instance
# with target value, or nil if not in tree.
# Optionally accepts a block and returns the
# first node encounted for which the block
# evaluates to true. This allows us to dfs
# search using arbitrary criteria.
class TreeNode
# ...
def dfs(target_value = nil, &blk)
# Depth-first search. Returns TreeNode instance
# with target value, or nil if not in tree.
# Optionally accepts a block and returns the
# first node encounted for which the block
# evaluates to true. This is useful when
# searching for nodes using attributes other
@jhamon
jhamon / broken_dfs.rb
Created September 21, 2013 07:14
This doesn't work because the block can't be passed recursively.
class TreeNode
# ... omitted.
def dfs(target_value = nil, &blk)
# A (broken) first attempt at depth-first search
# with arbitrary search criteria defined by the
# block received.
return self if !blk.nil && blk.call(@value)
return self if @value == target_value
@jhamon
jhamon / treenode.rb
Last active December 23, 2015 14:19
A simple implementation of nodes in a tree. Each tree can have arbitrarily many child nodes.
class TreeNode
attr_accessor :parent, :children
attr_reader :value
def initialize(value)
@value = value
@parent = nil
@children = []
end
def mymethod3(&blk)
puts "Hello from inside method 3"
yield
end
mymethod3 do
puts "I'm part of a block."
puts "I get evaluated by mymethod3 even"
puts "though a procified block is never"
puts "explicitly called by the method."
def mymethod2(prc)
puts "Hello from inside mymethod2."
puts "Calling the Proc object returns #{prc.call}"
end
prc = Proc.new { puts "I'm a proc." }
mymethod2(prc)
# Outputs:
# Hello from inside mymethod2.
def mymethod(&blk) #Expects a block argument
puts "Hello from inside mymethod."
puts "Your block returns #{blk.call}"
end
mymethod do
puts "Hello from a block."
puts "I was to_proc'd and then called like a proc object."
end
## Mutable objects as hash keys: probably a bad idea.
silly_array = ['fox', 'cow', 'moose']
another_ref = silly_array
# These variable names refer to the same object
silly_array.object_id == another_ref.object_id # => true
# Even though it doesn't seem like a great idea,
# ruby will let us use mutable objects, like
@jhamon
jhamon / object_ids_and_mutability.rb
Created September 18, 2013 05:09
W1D2 - References, object_id, and mutability
## Be careful when referencing mutable objects
a = {} # => {}
b = a # => {}
a.object_id # => 70132601471180
b.object_id # => 70132601471180
a[:foo] = 'bar' # => "bar"
b # => {:foo=>"bar"} # Woah!