Skip to content

Instantly share code, notes, and snippets.

@mark
Last active December 24, 2015 23:59
Show Gist options
  • Save mark/6883954 to your computer and use it in GitHub Desktop.
Save mark/6883954 to your computer and use it in GitHub Desktop.
A simple pointer class

Pointer class

Motivation:

Using #tap to operate on and return a value is a useful technique for clean code in Ruby. However, sometimes the value you want to return changes, or you don't even know it at the start. In those cases, you can't use #tap.

This Pointer class defines a #tapp method. #tapp takes a block, just like tap. However, the pointer yielded to the block can be assigned and reassigned using <=, and that assigned value is what is returned from #tapp, not the pointer itself.

class Pointer
##############
# #
# Initialize #
# #
##############
def initialize(obj = nil)
@object = obj
end
#############
# #
# Operators #
# #
#############
def <=(obj)
@object = obj
end
def ~
@object
end
####################
# #
# Instance Methods #
# #
####################
def tapp
yield(self)
~self
end
end
gem 'minitest'
require 'minitest/autorun'
require_relative 'pointer.shard.rb'
describe Pointer do
describe :~ do
it "defaults to nil" do
(~Pointer.new).must_be_nil
end
it "can be assigned in the constructor" do
(~Pointer.new(:foo)).must_equal :foo
end
end
describe :<= do
it "assigns the pointed value" do
ptr = Pointer.new
ptr <= :foo
(~ptr).must_equal :foo
end
end
describe :tapp do
it "yields itself" do
yielded = nil
pointer = Pointer.new
pointer.tapp do |ptr|
yielded = ptr
end
yielded.must_equal pointer
end
it "returns the last assigned value" do
Pointer.new.tapp do |ptr|
ptr <= :foo
ptr <= :bar
end.must_equal :bar
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment