Skip to content

Instantly share code, notes, and snippets.

View cwgem's full-sized avatar

Chris White cwgem

View GitHub Profile
@cwgem
cwgem / data.rb
Created July 28, 2011 11:33
不思議なDATA
require 'yaml'
state = DATA.read
state = (state.empty?) ? [] : YAML::load(state)
state << 1
puts state.inspect
code = File.new(__FILE__).readlines
code = code[0..(code.find_index{ |x| /\A__END__\s*\z/ =~ x })].join("") << "\n" << YAML::dump(state)
@cwgem
cwgem / class.c
Created July 28, 2011 14:04
Class Hierarchy
static VALUE
boot_defclass(const char *name, VALUE super)
{
extern st_table *rb_class_tbl;
VALUE obj = rb_class_boot(super);
ID id = rb_intern(name);
rb_name_class(obj, id);
st_add_direct(rb_class_tbl, id, obj);
rb_const_set((rb_cObject ? rb_cObject : obj), id, obj);
@cwgem
cwgem / gist:1111942
Created July 28, 2011 16:57
社員クラス
class Employee
attr_accessor :first_name
attr_accessor :last_name
attr_accessor :monthly_sales
def to_s
"#{@first_name} #{@last_name}: #{@monthly_sales}"
end
end
@cwgem
cwgem / gist:1111961
Created July 28, 2011 17:04
Comparableの使用例
class Employee
attr_accessor :first_name
attr_accessor :last_name
attr_accessor :monthly_sales
include Comparable
# 月間売上高で社員をソート
def <=>(other_employee)
other_employee.monthly_sales <=> @monthly_sales
end
@cwgem
cwgem / gist:1111966
Created July 28, 2011 17:05
ランダムデータ
# ランダム数 最小-最大
def range_rand(min,max)
min + rand(max-min)
end
# ランダム名前
$names = File.new('names.txt', 'r').readlines.map {|line| line.chomp}
def rand_name
$names[rand($names.length)]
end
@cwgem
cwgem / gist:1111976
Created July 28, 2011 17:08
実行結果
# ソート前
puts employees.inspect
# ソート後
puts employees.sort.inspect
# ※ご注意:これはランダムデータなので毎回結果がランダムとなります。
# [Alec Earl: 3030, Jayce Moises: 8373, Ronald Cornelius: 6653]
# [Jayce Moises: 8373, Ronald Cornelius: 6653, Alec Earl: 3030]
@cwgem
cwgem / custom_sort.rb
Created July 28, 2011 17:09
カスタムソートのフールソース
class Employee
attr_accessor :first_name
attr_accessor :last_name
attr_accessor :monthly_sales
include Comparable
# 月間売上高で社員をソート
def <=>(other_employee)
other_employee.monthly_sales <=> @monthly_sales
end
@cwgem
cwgem / names.txt
Created July 28, 2011 17:10
ランダム名前メソッドのデータファイル
Aaron
Abdiel
Abdullah
Abel
Abraham
Abram
Adam
Adan
Addison
Aden
@cwgem
cwgem / gist:1114534
Created July 29, 2011 19:21
Ruby arch differences for numeric types
irb(main):001:0> puts RUBY_VERSION + " " + RUBY_PLATFORM + " " + RUBY_PATCHLEVEL.to_s
1.9.2 x86_64-darwin10.8.0 290
=> nil
irb(main):002:0> 12345678987654321.class
=> Fixnum
irb(main):001:0> puts RUBY_VERSION + " " + RUBY_PLATFORM + " " + RUBY_PATCHLEVEL.to_s
1.9.4 i686-linux -1
=> nil
irb(main):002:0> 12345678987654321.class
@cwgem
cwgem / deconstructor.rb
Created July 30, 2011 14:53
Ruby Deconstructor
include ObjectSpace
class DestructorExample
def initialize(name)
define_finalizer self, proc { |id| puts "Instance #{name} Destroyed!" }
end
end
define_finalizer DestructorExample, proc { |id| puts "Class Desroyed!" }