Skip to content

Instantly share code, notes, and snippets.

View pasberth's full-sized avatar

pasberth pasberth

View GitHub Profile
@pasberth
pasberth / enumint.rb
Created September 15, 2011 04:42
あのさー、Integerはべつにこうでもよくね??
class Integer
include Enumerable
def each(&blk)
times(&blk)
end
end
if __FILE__ == $PROGRAM_NAME
require "test/unit"
@pasberth
pasberth / void.rb
Created September 15, 2011 09:37
戻り値がnilであることを保証するだけのdefine_method
class Object
def self.void funcname, &func
define_method(funcname) { |*args| func.call(*args); nil }
end
end
if __FILE__ == $PROGRAM_NAME
require "test/unit"
class SampleClass
void :homuhomu do |str|
$str = str
@pasberth
pasberth / overload.rb
Created September 16, 2011 13:05
オーバーロードっぽいことをする
# -*- coding: utf-8 -*-
def Object.defun(symbol, *signature, &blk)
instance_variable_set(:@overloaded_methods, {}) if @overloaded_methods.nil?
klass = self
unless @overloaded_methods.key? symbol
@overloaded_methods[symbol] = {}
# super()を使ったり、実際のメソッドと同じ挙動にするにはdefine_methodを使うしかないので
overload = Proc.new { |*args|
oms = klass.instance_variable_get(:@overloaded_methods)
sig = Signature.new(*args)
@pasberth
pasberth / iffattrs.rb
Created September 16, 2011 15:04
指定したメンバがすべて同値の場合に == が true を返す attr_reader みたいな
class Class
def iffattrs *attrs
define_method(:==) do |other|
attrs.each do |attr|
symbol = :"@#{attr}"
return false if instance_variable_get(symbol) != other.instance_variable_get(symbol)
end
true
end
@pasberth
pasberth / iffattrs.py
Created September 22, 2011 14:03
Python版の iffattrs
def iffattrs(cls, *attrs):
def _iffattrs(self, other):
for name in attrs:
if not hasattr(self, name) or not hasattr(other, name):
return False
if getattr(self, name) != getattr(other, name):
return False
return True
cls.__eq__ = _iffattrs
@pasberth
pasberth / winreq.rb
Created September 23, 2011 13:06
とりあえず書いてみた
# あらゆる require より後に定義する
# これより前に定義されたあらゆるrequireが失敗した場合、パスの名前をwinに変えてリトライする
module Kernel
alias win_path_original_require require
def require path
win_path_original_require path
rescue LoadError => e
win_path_original_require to_win_path path
@pasberth
pasberth / initbefore.rb
Created September 29, 2011 08:59
よくしたくなるシチュエーションを関数化
class Class
def initbefore &process
allocate.tap do |instance|
instance.instance_eval &process
end
end
end
@pasberth
pasberth / defarray.rb
Created September 30, 2011 09:07
2次元配列を楽に作りたくて作った
class Array
alias defarray_original_at []
alias defarray_original_initialize initialize
def initialize *args, &blk
return defarray_original_initialize(*args, &blk) unless args.empty?
@default_handler = blk
end
# -*- coding: utf-8 -*-
module Kernel
def method_missing funcname, *args, &blk
if funcname =~ /\A画面に「(.*)」と表示してくださいですわ\z/
puts $1
else
super
end
end
@pasberth
pasberth / synciter.rb
Created October 4, 2011 14:12
2つ以上のEnumerableを同時に繰り返す
# -*- coding: utf-8 -*-
class SynchronizedIterator
include Enumerable
def initialize *enumerables
@enumerables = enumerables.map do |e|
e.map { |item| item }
end