2000-05-01から1ヶ月間の記事一覧

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

備忘録目次 - ロバの耳ハッシュで単方向リンクリストを作って,それを操作する. # 先祖を探す.リストには自分を含める 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の出力結果を見ると微妙に不定のような.

ハッシュのエントリを処理する

備忘録目次 - ロバの耳 h = { 'Apple' => 'red', 'Banana' => 'yellow', 'Lemon' => 'yellow', 'Carrot' => 'orange' } h.each_key {|key| p "#{key} is #{h[key]}."} h.each_pair {|key, val| p "#{key} is #{val}."} # 出力結果はいずれも #=> "Lemon is y…

ハッシュからエントリを削除する

備忘録目次 - ロバの耳 h = { 'Apple' => 'red', 'Banana' => 'yellow', 'Lemon' => 'yellow', 'Carrot' => 'orange' } p h.delete('Banana') #=>"yellow" p h #=> {"Lemon"=>"yellow", "Carrot"=>"orange", "Grape"=>"purple", "Apple"=>"red"}

ハッシュ内にキーが存在するかどうか調べる

備忘録目次 - ロバの耳 h = { 'Apple' => 'red', 'Banana' => 'yellow', 'Lemon' => 'yellow', 'Carrot' => 'orange' } p h.key?('Lemon') #=> true p h.key?('Peach') #=> false p (h['Apple'])? 'TRUE': 'FALSE' #=> "TRUE" p (h['Eggplant'])? 'TRUE': 'F…

配列からハッシュを作る

a1 = %w[A B C] a2 = %w[1 2 3] a3 = a1.zip(a2).flatten h1 = Hash[*a3] p a3 #=> ["A", "1", "B", "2", "C", "3"] p h1 #=> {"A"=>"1", "B"=>"2", "C"=>"3"}

ハッシュに要素を追加する

備忘録目次 - ロバの耳 h = { 'Apple' => 'red', 'Banana' => 'yellow', 'Lemon' => 'yellow', 'Carrot' => 'orange' } h['grape'] = 'purple' # 追加 p h #=> {"grape"=>"purple", "Lemon"=>"yellow", "Carrot"=>"orange", "Apple"=>"red", "Banana"=>"yell…