【Ruby】ハッシュ
この辺もperlでよく使っていたので。。。
(1)単純なパターン
①ソース(hash.rb)
hash = Hash.new() # ハッシュの初期化
hash[:apple] = 1 # 要素の挿入
hash[:orange] = 2
hash[:grape] = 3
puts hash[:apple] # keyを指定してvalueを取り出し
puts '----------------'
hash.each do |key,val| # keyとvalueを順番に取り出し
puts "#{key}: #{val}"
end
hash[:strawberry] = 4; # ハッシュに要素を追加
puts '----------------'
hash.each do |key,val| #再度keyとvalueを順番に取り出し
puts "#{key}: #{val}"
end
②実行結果
# ruby hash.rb
1
----------------
apple: 1
orange: 2
grape: 3
----------------
apple: 1
orange: 2
grape: 3
strawberry: 4
(2)ネストしたハッシュ
①ソース(hash_nest.rb)
hash = Hash.new { |hash,key| hash[key] = Hash.new {} } # ハッシュの初期化
hash[:apple][:count] = 2; # 要素の挿入
hash[:apple][:price] = 50;
hash[:orange][:count] = 5;
hash[:orange][:price] = 100;
hash[:grape][:count] = 10;
hash[:grape][:price] = 30;
puts hash # とりあえず出力
puts '----------------'
hash.each do |key,arr| #各要素を取り出し
arr.each do |item,value|
puts "#{key}: #{item},#{value}"
end
end
hash[:strawberry][:count] = 4; # 要素を追加
hash[:strawberry][:price] = 200;
puts '----------------'
puts hash
puts '----------------'
hash.each do |key,arr| #再度各要素を取り出し
arr.each do |item,value|
puts "#{key}: #{item},#{value}"
end
end
②実行結果
# ruby hash_nest.rb
{:apple=>{:count=>2, :price=>50}, :orange=>{:count=>5, :price=>100}, :grape=>{:count=>10, :price=>30}}
----------------
apple: count,2
apple: price,50
orange: count,5
orange: price,100
grape: count,10
grape: price,30
----------------
{:apple=>{:count=>2, :price=>50}, :orange=>{:count=>5, :price=>100}, :grape=>{:count=>10, :price=>30}, :strawberry=>{:count=>4, :price=>200}}
----------------
apple: count,2
apple: price,50
orange: count,5
orange: price,100
grape: count,10
grape: price,30
strawberry: count,4
strawberry: price,200
perlとかPHPだと特に意識しないでネストしたハッシュを定義できたんですが、rubyの場合はHash.newをやらないとエラーになっちゃうんですね^^;