2006-12-05から1日間の記事一覧

\C-a

Rubyで\C-aと書くとCTRL+Aを表す。\C-Aと書いてもよい。はじめに?をつけると文字リテラル。 p ?\C-a == ?\C-A #=> true p "\C-a"[0] == ?\C-A #=> true p "\x1"[0] == ?\C-A #=> true p "\x1" == "\C-A" #=> true

String#each_byteとString#scanの違い

String#each_byteだと、Fixnumとして各文字を切り出しますが、scanはStringとして切り出します。 s = "Rubyco!" s.each_byte do |x| puts "#{x} (#{x.class})" end s.scan(/./) do |c| puts "#{c} (#{c.class})" end実行結果です。 82 (Fixnum) 117 (Fixnum)…

単語の頻度を調べる

class String def words(pattern=/\w+/) hash = Hash.new(0) self.scan pattern do |w| hash[w] += 1 end hash end end s = <<"EOD" We wish you a Merry Christmas, We wish you a Merry Christmas, We wish you a Merry Christmas, and A Happy New Year! …