Skip to content

Instantly share code, notes, and snippets.

View havenwood's full-sized avatar
:octocat:

Shannon Skipper havenwood

:octocat:
View GitHub Profile
@havenwood
havenwood / constants_hash.rb
Created April 17, 2014 04:02
Object#constants_hash.
class Object
def constants_hash
constants = self.constants
constant_values = constants.map do |const|
self.const_get const
end
constants.zip(constant_values).to_h
end
end
@havenwood
havenwood / gemfile.rb
Created May 21, 2014 00:55
Find Bundler gems in a given dependency group.
require 'bundler'
class Gemfile
def initialize gemfile_path = 'Gemfile'
@bundler = Bundler::Dsl.new
@bundler.eval_gemfile gemfile_path
end
def gems group
@bundler.dependencies.select do |gem|
@havenwood
havenwood / capture_stdout.rb
Created May 23, 2014 19:14
Capture stdout example.
require 'stringio'
module Capture
def self.stdout &block
$stdout = captured_stdout = StringIO.new
block.call
captured_stdout
ensure
$stdout = STDOUT
block.call
@havenwood
havenwood / getarrow.rb
Created May 23, 2014 21:09
Detect an arrow key press.
require 'io/console'
ARROWS = {"[A"=>:up, "[B"=>:down, "[C"=>:right, "[D"=>:left}
char = STDIN.getch
ARROWS[STDIN.read_nonblock(2)] if char == "\e"
@havenwood
havenwood / weasel.rb
Last active August 29, 2015 14:02 — forked from jlindsey/weasel.rb
class Weazel
CHARS = [*'A'..'Z', ' ']
def initialize target
@target = target
@best = Array.new(28) { CHARS.sample }.join
end
def call
0.upto Float::INFINITY do |n|
@havenwood
havenwood / rock_paper_scissors.rb
Created June 8, 2014 15:36
Rock, Paper, Scissors
class RockPaperScissors
OPTIONS = [:rock, :paper, :scissors]
include Comparable
attr_reader :hand
def initialize
@hand = OPTIONS.sample
end
@havenwood
havenwood / point.rb
Created July 26, 2014 03:06
Point Equalizer Struct
require 'equalizer'
Point = Struct.new(:x, :y) { include Equalizer.new(*members) }
Point.new(0, 0)
#=> #<struct Point x=0, y=0>
Point.new(0, 0) == Point.new(0, 0)
#=> true
@havenwood
havenwood / equalizable_struct.rb
Created July 26, 2014 03:48
An EqualizableStruct with Equalizer
require 'equalizer'
class EqualizableStruct < Struct
def initialize *args, &block
class << self
include Equalizer.new(*members)
end
super
end
class Future
def initialize &work
@worker = Thread.new &work
end
def ready?
@worker.alive?
end
def value
@havenwood
havenwood / client.rb
Last active August 29, 2015 14:04
Playing around with Rinda TupleSpace
require_relative 'tuplespace'
DRb.start_service
space = TupleSpace.new tuple_space: DRbObject.new(nil, 'druby://0.0.0.0:3000')