Skip to content

Instantly share code, notes, and snippets.

View hannestyden's full-sized avatar

Hannes Tydén hannestyden

  • Stockholm, Sweden
View GitHub Profile
# Yehuda Katz' magic alias_method_chain remover.
module NewSuperExtend
# Wedges `nodule` into the ancestor chain for the instance.
def new_super_extend(nodule)
# `define_method` used since we want to keep the lexical scope.
(class << self; self; end).send(:define_method, :new) do |*arguments, &block|
super(*arguments, &block).extend(nodule)
end
end
end
class Percent < Struct.new(:percent)
def of(total)
total * normalized
end
def coerce(other)
[ other, of(other) ]
end
def +(other)
@hannestyden
hannestyden / post-checkout
Created October 28, 2010 11:26
Prints a random line from the bridge of Metallica's "Master of Puppets" when checking out the master branch.
#!/bin/sh
# .git/hooks/post-checkout
# chmod +x .git/hooks/post-checkout
if [ $(git symbolic-ref HEAD | cut -d '/' -f 3) == 'master' ]; then
lines[0]="Master, Master, where's the dreams that I've been after?"
lines[1]="Master, Master, you promised only lies"
lines[2]="Laughter, laughter, all I hear or see is laughter"
lines[3]="Laughter, laughter, laughing at my cries"
echo " ${lines[$((RANDOM%${#lines[*]}))]}";
# What's the fuzz about refinements
# It's practically there already, except for literals.
module MyWorld # Where everything is a bit backwards
module ReverseOnInpection
def inspect
super.reverse
end
end
Interval =
Struct.new(:a, :b) do
def +(other)
sibling(*(zip(other) { |(c, d)| c + d }))
end
def -(other)
sibling(*(zip(other) { |(c, d)| c - d }))
end
@hannestyden
hannestyden / array_count_by.rb
Created January 10, 2011 10:02
Count elements in an Array
module ArrayCountBy
def count_by(&block)
self.group_by(&block).map { |k, vs| [ k, vs.size ] }.inject({}) do |memo, (key, size)|
memo.update(key => size)
end
end
end
Array.send(:include, ArrayCountBy)
@hannestyden
hannestyden / pp_json.rb
Created January 20, 2011 16:32
Ubersimple pretty print for JSON.
#! /usr/bin/env ruby
# Ubersimple pretty print for JSON.
# Hannes Tydén, hannes@soundcloud.com
# 2011-01-20
# No warranty, no nothing.
# Have fun.
require 'json'
ps x | grep 'Flash Player Plugin for Chrome' | awk '{ print $1 }' | xargs kill
def sieve_of_euler(list)
if list.empty?
list
else
out = list - (list.map { |e| e * list.first })
[ out.first ] + sieve_of_euler(out[1..-1])
end
end
sieve_of_euler((2..30).to_a) # => [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
@hannestyden
hannestyden / clever_compact.rb
Created March 1, 2011 19:00
Being clever is always fun.
def upperbound(value, max)
[ value, max ].compact.min
end
upperbound(1, 5) # => 1
upperbound(5, 5) # => 5
upperbound(10, 5) # => 5
upperbound(10, nil) # => 10
def lowerbound(value, min)