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 / redirect_stdout.rb
Created February 2, 2014 23:38
Capture $stdout for a while.
require 'stringio'
def capture
old_stdout, $stdout = $stdout, StringIO.new
fake_stdout = $stdout
yield
$stdout = old_stdout
fake_stdout.string
end
@havenwood
havenwood / exposing_an_instance_variable.rb
Created February 3, 2014 00:32
Exposing an instance variable.
module Mushroom
@color = :blue
def self.color
@color
end
def self.color=(this_color)
@color = this_color
end
class Integer
def collatz_chain_size
n = self
chain = []
until n == 1
chain << n
n.even? ? n /= 2 : n = n * 3 + 1
end
[chain.size, chain.first]
end
@havenwood
havenwood / chemical_prime.rb
Last active August 29, 2015 13:56
Prime Number Chemistry
# http://users.minet.uni-jena.de/~dittrich//p/Dit2005upp.pdf
# https://github.com/videlalvaro/erlang-prime-sieve
require 'mathn'
module ChemicalPrime
def self.take n
sequence(n).map { |n| n * 2 + 1 }.unshift 2
end
@havenwood
havenwood / blink.rb
Created February 18, 2014 05:23
curseless <blink> with backspaces
@havenwood
havenwood / arity_range.rb
Last active August 29, 2015 13:56
Ask a method, lambda or proc for the range of arguments it can be called with from minimum to maximum.
module ArityRange
def arity_range
args = parameters.map &:first
req = args.count :req
opt = args.include?(:rest) ? Float::INFINITY : args.count(:opt)
keyreq = args.count :keyreq
keyopt = args.include?(:keyrest) ? Float::INFINITY : args.count(:key)
@havenwood
havenwood / peek_at.rb
Last active August 29, 2015 13:56
Enumerable#peek_at an index.
module Enumerable
def peek_at index
value, _ = each_with_index.select { |_, i| index == i }.first
value
end
end
@havenwood
havenwood / iterator.rb
Last active August 29, 2015 13:56
Iterator beginning at `element` and iterating by `increment`.
module Iterator
def self.new element, increment = 1
Enumerator.new do |iteration|
loop do
iteration << element
increment.abs.times do
element = if increment >= 0
element.next if element.respond_to? :next
else
if element.respond_to? :pred
@havenwood
havenwood / birthday_paradox.rb
Last active August 29, 2015 13:57
Birthday Paradox
class Bdays
attr_reader :birthdates
def initialize n
@birthdates = Array.new(n) { [*0..365].sample }.map do |s|
birthday = Time.new(0) + s * 60 * 60 * 24
[birthday.month, birthday.day]
end
shared_birthdates
@havenwood
havenwood / array_iteration.rb
Last active August 29, 2015 13:59
Array #next, #pred and #rewind.
module ArrayIteration
def next
@index ||= 0
raise StopIteration, 'iteration reached an end' if @index.next > size
@index += 1
self[@index.pred]
end
def pred
@index ||= 0