Skip to content

Instantly share code, notes, and snippets.

module Chapter08
module ReplaceTypeCodeWithStateOrStrategy
class RigidMountainBike
def initialize(params)
@tyre_width = params[:tyre_width]
end
def off_road_ability
@tyre_width * MountainBike::TYRE_WIDTH_FACTOR
end
# Yet another version with suggestions from workmad3 :-)
# This time, pass in the keyword args into the block.
# This means duplicating the definition of valid params, but
# also means you get normal local variables in the method body.
module DefK
# NOTE: params is for syntactic sugar, and has no bearing on the
# number of arguments you can call
def def_k(method_name, *params, kparams, &method_body)
define_method method_name do |*args|
@ashmoran
ashmoran / make_me_an_animal_class.rb
Created October 16, 2010 18:30
Example of metaprogramming to create an entire class dynamically without `Kernel.eval`
def make_me_an_animal_class(name, property)
klass = Class.new
klass.class_eval do
define_method(:initialize) do |attribute|
instance_variable_set("@#{property}", attribute)
end
define_method(property) do
instance_variable_get("@#{property}")
class ArduinoInterpreter
def initialize(setup_block, tick_block)
@setup_block, @tick_block = setup_block, tick_block
end
def serial_begin
puts "Initialising serial port..."
end
def serial_write(data)
@ashmoran
ashmoran / sicp_exercise_1_11.scm
Created December 23, 2010 23:19
SICP exercise 1.11
(define (f n)
(cond ((= n 1) 1)
((= n 2) 2)
((= n 3) 3)
(else (+ (f (- n 1))
(* 2 (f (- n 2)))
(* 3 (f (- n 3))))))
)
(define (g n)
@ashmoran
ashmoran / sicp_exercice_1_22.scm
Created January 4, 2011 21:42
SICP exercise 1.22
(define (expect actual expectation expected)
(display "• ")
(display actual)
(display " should equal ")
(display expected)
(display ": ")
(expectation actual expected)
(display "pass\n")
)
@ashmoran
ashmoran / sicp_exercise_1_22.scm
Created January 6, 2011 23:12
SICP exercise 1.22 - A surprising performance discovery
; Slow! The (next) "optimisation" slows it down
(define (find-divisor n test-divisor)
(define (next n)
(if (= n 2)
3
(+ n 2)))
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (next test-divisor)))))
@ashmoran
ashmoran / sicp_exercise_1_31.scm
Created January 7, 2011 22:01
SICP exercise 1.31
(define (expect actual expectation expected)
(display "• ")
(display actual)
(display " should equal ")
(display expected)
(display ": ")
(expectation actual expected)
(display "pass\n")
)
@ashmoran
ashmoran / sicp_exercise_1_35.scm
Created January 7, 2011 23:59
SICP exercise 1.35
(define (expect actual expectation expected)
(display "• ")
(display actual)
(display " should equal ")
(display expected)
(display ": ")
(expectation actual expected)
(display "pass\n")
)