2006-03-08から1日間の記事一覧

YAML

RubyのオブジェクトをYAMLで保存してみました。 require 'yaml' a = [ 'Alice', 'Bobby', [ 'Chris', 'Charlie' ], 'David' ] h = { 'Alice' => 14, 'Bob' => 14, 'Chris' => 21 } x = [ a, h ] y = nil open("sample.yml", "w") do |w| YAML::dump(x, w) en…

配列添字の限界

Rubyでは配列の添字に限界はあるのでしょうか。 倍々ゲームで探索しましょう。 a = Array.new (1..64).each do |n| index = 2 ** n print "#{index}, " a[index] = 1 endでも、やっているうちにディスクアクセスが止まらなくなってしまい、あわててCTRL+Cで…

クラスメソッド

Rubyのクラスメソッドは、クラスオブジェクトの特異メソッドです。 class Rubyco def self.hello puts "Hello!" end end Rubyco.hello #=> Hello!こう書くこともできます。 class Rubyco end def Rubyco.hello puts "Hello!" end Rubyco.hello #=> Hello!ク…

たださんからリンク

tDiaryのただただしさんからリンクしていただきました。ありがとうございます。 「メタ方面」に関するたださんの想像はほぼ当たっているのですが、「その道具を使うことによって、自分の表現力や思考パターンがどう変化するか」というポイントも自分にとって…

rescueでのretry

rescue節(?)でretryすると、リトライします。 以下は、例外を使った(不器用な)ポーリングです。 message = nil t = Thread.start { sleep 3 message = "Hello!" } begin if message puts message else raise "Message is not ready." end rescue puts $! sle…

ifを作る

ifのようなif_を作ってみました。単にyieldの練習です。 def if_(c) if c yield end end cond = true if_(cond) { puts "A" }でも、以下のwhile_はwhileの代わりにはなりません。無限ループになってしまいます♪ def while_(c) while c yield end end i = 0 w…

profile

プロファイラを使うと、プログラムのボトルネックを見つける助けになります。 Windowsのコマンドラインから以下のようにします。2>と書いているのは標準エラー出力をファイルにリダイレクトするためです。 ruby -r profile a.rb 2> result.txt以下はa.rbの内…

チェックサム

am

昔懐かし(?)チェックサムを表示するプログラムです。 class ChecksumPrinter def initialize(io, columns = 16, rows = 16) @columns, @rows = columns, rows @buffer_size = @columns * @rows @sums = Array.new(@buffer_size) @io = io @io.binmode end de…

グレイコード

am

指定したビット数のグレイコード表を作ります。 def gray_table(n) fmt = sprintf("%%0%db\n", n) (0...(1 << n)).each do |i| printf(fmt, i ^ (i >> 1)) end end gray_table(5)実行結果です。 00000 00001 00011 00010 00110 00111 00101 00100 01100 0110…

バイナリサーチ

am

Rubyでバイナリサーチを実装しました。本来はSortedListクラスのメソッドのような気もしますが、とりあえず関数風味で♪ def bsearch(sorted, target, if_none = nil, &cmp) cmp ||= proc { |a, b| a <=> b } left, right = 0, sorted.length while left < ri…

Mutex

Mutex#lock, Mutex#unlockとbegin ... ensure ... endでクリティカルセクションを作りました。 require 'thread' M = Mutex.new def normal(c) 10.times { print '.' sleep rand(nil) / 10 } end def critical(c) c = c.upcase M.lock begin print "(" 10.ti…