Objects from Scratch

Look ma, I made my own object! It doesn’t handle state that well, but at least it can be passed messages and told to do things.

def make_number(x)
  lambda do |op, *y|
    if op == '+'
      make_number(x + y[0])
    elsif op == '-'
      make_number(x - y[0])
    elsif op == 'val'
      x
    end
  end
end

my_num = make_number(5)         => <#Proc>
my_num.call('+', 7).call('val') => 12

In case you can’t tell, this object creation makes use of higher order procedures. The make number procedure returns the anonymous procedure created by lambda. This form of object creation is not terribly practical, but it sure is cool.

Leave a Comment