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 |
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 |
View blink.rb
def blink string, duration: 4, interval: 0.5 | |
start = Time.now | |
while Time.now < start + duration | |
print string | |
sleep interval | |
[?\r, ?\s, ?\r].each { |char| print char * string.size } | |
sleep interval | |
end | |
end |
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) |
View peek_at.rb
module Enumerable | |
def peek_at index | |
value, _ = each_with_index.select { |_, i| index == i }.first | |
value | |
end | |
end |
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 |
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 |
OlderNewer