Skip to content

Instantly share code, notes, and snippets.

View pasberth's full-sized avatar

pasberth pasberth

View GitHub Profile
@pasberth
pasberth / in.rb
Created November 8, 2011 16:58
if item.in enum then A else B end
class Object
def in enum
enum.include? self
end
end
if 'a'.in ['a', 'b', 'c']
puts 'hello'
end
# => hello
@pasberth
pasberth / definit.rb
Created November 9, 2011 11:43
コンストラクタでの初期化の一部を肩代わりしてくれるdefinit.rb
class Class
def definit *params, &initialize
define_method :initialize do |*args, &blk|
until params.empty?
instance_variable_set :"@#{params.shift.to_sym}", args.shift
end
initialize && instance_exec(*args, &initialize)
end
end
@pasberth
pasberth / findnum.rb
Created November 15, 2011 06:44
Array#=~ メソッドはこういう挙動であるべき的な
class Object
def in? enum
enum.include? self
end
end
module Enumerable
@pasberth
pasberth / hello.rb
Created November 19, 2011 03:00
requireでオプションを指定できるといいなーと思った
$options = { you: nil }.merge $options || {}
if $options[:you]
puts "hello #{$options[:you]}"
else
puts "hello guest"
end
@pasberth
pasberth / original.rb
Created November 19, 2011 06:15
alias xxx_original_require require みたいなことをしても済むように作った
class Module
def original method
original_methods = Hash.new do |original_methods, method|
original_methods[method.to_sym] = original_method = []
define_method :"original_#{method.to_sym}" do |*args, &blk|
fail if original_method.empty?
tmp = original_method.pop
res = tmp.call *args, &blk
@pasberth
pasberth / matchary.rb
Created November 22, 2011 03:14
Array#=== をかっこ良く
class Array
def === other
zip(other.to_ary).all? { |mine, theirs| mine === theirs }
end
end
puts case [:lover, 'mana', 18]
when [Symbol, String, Integer] then 'love!'
@pasberth
pasberth / hello.rb
Created November 22, 2011 04:22
RubyLexを触ってみた結果
class Hello
def hello_world *args
puts "hello", *args
end
end
@pasberth
pasberth / dec.rb
Created November 24, 2011 07:38
デコレータ
# -*- coding: utf-8 -*-
class Module
private
def decorators
@decorators ||= []
def decorator *args, &blk
@pasberth
pasberth / each_of.rb
Created November 29, 2011 04:45
こんなの便利だなあって思った
module Enumerable
def each_of key, &blk
return Enumerator.new self, :each_of, key unless block_given?
each do |e|
blk.call e[key]
end
end
end
res = [[1, 2], [3, 4]].each_of(0).map do |i|
@pasberth
pasberth / define.rb
Created December 2, 2011 03:26
前こんなの考えたのを思い出した
# -*- coding: utf-8 -*-
class Module
def define(consname, value=nil, &blk)
if value
const_set(consname, value)
else
define_method(consname, &blk)
end
end