ruby

ファイルを行単位で逆向きに読む

a = open('test.txt').readlines() # 全部の行を読む a.reverse.each {|x| p x.chomp} # 逆順に表示 eachを逆順に実行するメソッドがあればいいのに. class Array def reverse_each (self.size-1).downto(0) {|i| yield self[i] } end end a = open('test.t…

ファイル内のすべての単語を処理する

普通に処理 open('test.txt').each {|x| x.split().each {|y| p y} } バカの一つ覚えのようにread open('test.txt').read().split(/\s+/).each {|x| p x }

ファイルの行数をカウントする

# 何行あるか? count = 0 open('test.txt').each {|x| count += 1} p count # 何個の\nがあるか数える. a = open('test.txt').read() p a.count("\n")

継続文字のある行を読む

手続き的なコード prev = '' open('test.txt').each {|x| x.chomp! if x[-1]!=?\\ p prev+x prev = '' else prev += x.chop end } p prev if prev.size>0 かっこ悪い… こっちのほうがマシ? a = open('test.txt').read() p a.gsub(/\\\n/, '').split("\n") …

読み取るバイト数を指定する

IO#read([length]) でバイト数を指定できる f = open('test.txt') p f.read(3) # 3バイト読む p f.read(1) f.close

出力をフラッシュする

IO#flush IO#fsync flushはアプリレベルで,fsyncはOSレベル?使わなそう.c/c++でなら,実行時間が長いアプリで途中結果を横から覗き込みたい.ハングしても途中結果は吐き出させたいというときに使うけど.

一時ファイルを使ってファイルを更新する

srcname = 'old.txt' tmpname = 'old.tmp' bakname = 'old.bak' dst = open( tmpname, 'w') # テンポラリ src = open( srcname) src.each {|x| # ここでxを加工する dst.puts x.downcase } src.close() dst.close() File.rename( srcname, bakname) # すでに…

フィルタを書く

$stdin.each {|l| puts l.chomp.downcase } 標準入力から受け取って小文字にして出力する.

一時ファイルを作成する

require 'tempfile' temp = Tempfile::new("foobar", "/home/tmp")未調査

標準エラー出力の先を変更

ferr = open("error.log", "a") # 追記モードで開く $stderr = ferr # 標準エラー出力を変更 $stderr.puts 'an error occurred!!!' # エラーの吐き出し $stderr = STDERR # 元に戻す ferr.close # 閉じる 直接 $stderrに代入して,閉じるのもrubyに任せる? …

ファイルをオープンする

f = open('test.txt') # ファイルをオープン f.close # ファイルを閉じる # open('test.txt','w') # 書き込みモードでファイルをオープン open('test.txt') {|f| } # ファイルは自動で閉じられる begin f = open('test_.txt') f.close rescue => err if err.…

文字列パターン内で,AND,ORを表現する

/re1|re2/ # re1かre2が含まれる文字列 /re1.*re2|re2.*re1/ # re1とre2が重複せずに両方含む文字列

連続する単語

re = /(foo|bar)\1/ p 'foofoo' =~ re #=> 0 p 'foobar' =~ re #=> nil p 'barfoo' =~ re #=> nil p 'barbar' =~ re #=> 0 re = /(foo|bar)(?!\1)(foo|bar)/ p 'foofoo' =~ re #=> nil p 'foobar' =~ re #=> 0 p 'barfoo' =~ re #=> 0 p 'barbar' =~ re #=> …

欲張りマッチと非欲張りマッチ

str = "<b>foo</b> <strike>bar</strike>" p str.gsub(/<.*>/, '') #=> "" p str.gsub(/<.*?>/, '') #=> "foo bar" {m} m回 {m,} m回以上 {m,n} m回以上,n回まで

ワイルドカードを正規表現にする

def wild_to_re( pat) Regexp.new( "\\A"+pat.gsub(/\./,'\\.').gsub(/\*/,'.*').gsub(/\?/,'.')+"\\z") end p wild_to_re( '*.*') #=> /\A.*\..*\z/ p wild_to_re( 'log????.txt') #=> /\Alog....\.txt\z/ これはライブラリの中をあされば,似たようなコー…

一定範囲の行を取り出す

perlには開始パターンと終了パターンを指定すると,その範囲を取り出せる演算子が存在するらしい. def range( a, s, e) def find(a, p) return a.index(p) unless p.kind_of? Regexp a.each_with_index {|x,c| return c if x =~ p } return nil end sl = fi…

n番めのマッチを見つける

# マッチするものの配列を作って,n番目を取り出す a = 'blue green red grern white'.scan(/\w+/) p "third color is #{a[2]}." if a.size>=2 # ループさせて,n番目にきたら処理する c = 0 'blue green red grern white'.gsub(/\w+/) { |x| c+=1; p "third…

正規表現にコメントをつける

p 'v1 = (6+5)*2; v2 = p->x;'.scan(/ [\w\.]+ # 英数字にマッチ | -> # アロー演算子(2文字以上の記号) | [^\s] # 1文字の記号 /x) 最後にxをつけると,正規表現中の空白が無視される.

単語にマッチさせる

p 'Seventh Avenue/Adam Clayton Powell Jr. Boulevard'.scan(/\w+/) #=> [["Seventh"], ["Avenue"], ["Adam"], ["Clayton"], ["Powell"], ["Jr"], ["Boulevard"]] '単語'という概念がアプリによって変わるので,単語とは何か?によって当然,正規表現も変わ…

文字にマッチさせる

r = /\A[A-Za-z]+\z/ p ['ABC' =~ r, 'ABC?' =~ r, '123' =~ r, '日本語' =~ r] #=> [0, nil, nil, nil] r = /\A[^\W\d_]+\z/ p ['ABC' =~ r, 'ABC?' =~ r, '123' =~ r, '日本語' =~ r] #=> [0, nil, nil, 0] 通常は前者で十分だけれど,特殊な文字(日本語と…

コピーと置換を同時に行ないたい

s1 = 'this is huge?' s2 = s1.sub(/this/, 'that') p s1 #=> "this is huge?" p s2 #=> "that is huge?" s3 = 'this is huge?' p s3.sub!(/this/, 'that') #=> "that is huge?" p s3.sub!(/this/, 'that') #=> nil 直接,対象の文字列を置換したい場合は,s…

概要

最低限の基本的なことを書くかも?予定地のみを確保.詳細は以下を参考に. プログラミング言語 Ruby リファレンスマニュアル http://www.namaraii.com/rubytips/?%A5%D1%A5%BF%A1%BC%A5%F3%A5%DE%A5%C3%A5%C1

データ間の関係を表現する

備忘録目次 - ロバの耳ハッシュで単方向リンクリストを作って,それを操作する. # 先祖を探す.リストには自分を含める def get_ancestor( h, c) ret = [c] while(true) c = h[c] return ret unless c ret << c end end # 子供を探す.自分は含めない def g…

最もよく現れるデータを見つけたい

備忘録目次 - ロバの耳 a = %w[ a a b o ab a ab o a] h = a.inject(Hash.new(0)) {|x,y| x[y]+=1; x} p h.to_a.sort_by {|x| [-x[1],x[0]] } ハッシュ表を使って出現頻度をカウントして,値でソートする.

2つのハッシュの両方にあるキー、または一方にしかないキーを見つける

備忘録目次 - ロバの耳 h1 = Hash[*%w[Apple red Tomato red Papper red]] h2 = Hash[*%w[Spinach green Celery green Papper green]] a1 = h1.keys a2 = h2.keys p a1 - a2 #=> ["Tomato", "Apple"] p a1 & a2 #=> ["Papper"] キーを取得してから 片方の配…

ハッシュをマージする

備忘録目次 - ロバの耳 h1 = Hash[*%w[Apple red Tomato red Papper red]] h2 = Hash[*%w[Spinach green Celery green Papper green]] p h1.merge(h2) #=> {"Celery"=>"green", "Tomato"=>"red", "Spinach"=>"green", "Apple"=>"red", "Papper"=>"green"} p …

ハッシュをソートする

キーでソートする h = Hash[*%w[Apple red Banana yellow Lemon yellow Carrot orange Grape purple]] a = h.keys.sort # キーを配列にしてソートする p a #=> ["Apple", "Banana", "Carrot", "Grape", "Lemon"] a.each{|x| p "#{x} is #{h[x]}"} #=> "Apple…

1つのキーに複数の値が対応するハッシュ

備忘録目次 - ロバの耳 def check_mutilple_value( v, test) return v.index(test) if v.kind_of? Array v == test end def get_food_by_color( h, c) ret = [] h.each_pair{|k,v| ret << k if check_mutilple_value(v,c)} ret end h = { 'Apple' => 'red', …

ハッシュを反転する

備忘録目次 - ロバの耳 h = { 'Apple' => 'red', 'Banana' => 'yellow', 'Lemon' => 'yellow', 'Carrot' => 'orange' } p h.invert #=> {"red"=>"Apple", "orange"=>"Carrot", "yellow"=>"Banana"} # 色がかぶっているので,その分消えている. h2 = {} h.ea…

ハッシュ要素を挿入した順に取り出す

備忘録目次 - ロバの耳eachで普通に取り出せてる?でもdeleteの出力結果を見ると微妙に不定のような.