Skip to content

Instantly share code, notes, and snippets.

Avatar
:octocat:

Shannon Skipper havenwood

:octocat:
View GitHub Profile
@havenwood
havenwood / redirect_stdout.rb
Created Feb 2, 2014
Capture $stdout for a while.
View redirect_stdout.rb
require 'stringio'
def capture
old_stdout, $stdout = $stdout, StringIO.new
fake_stdout = $stdout
yield
$stdout = old_stdout
fake_stdout.string
end
View exposing_an_instance_variable.rb
module Mushroom
@color = :blue
def self.color
@color
end
def self.color=(this_color)
@color = this_color
end
View euler14.rb
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 Aug 29, 2015
Prime Number Chemistry
View chemical_prime.rb
# 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 Feb 18, 2014
curseless <blink> with backspaces
View blink.rb
@havenwood
havenwood / arity_range.rb
Last active Aug 29, 2015
Ask a method, lambda or proc for the range of arguments it can be called with from minimum to maximum.
View arity_range.rb
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 Aug 29, 2015
Enumerable#peek_at an index.
View peek_at.rb
module Enumerable
def peek_at index
value, _ = each_with_index.select { |_, i| index == i }.first
value
end
end
@havenwood
havenwood / iterator.rb
Last active Aug 29, 2015
Iterator beginning at `element` and iterating by `increment`.
View iterator.rb
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
View birthday_paradox.rb
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 Aug 29, 2015
Array #next, #pred and #rewind.
View array_iteration.rb
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
You can’t perform that action at this time.