Hatena::Grouprubyist

てーげーRuby

2008-06-30

練習問題 ハッシュ(後半)

| 19:36

(5) 順番を保存するハッシュ、OrderdHashクラスを定義してください。

こんなんでいいでしょうか。

  1 class OrderdHash
  2   include Enumerable
  3
  4   def initialize
  5     @hash_ary = []
  6   end
  7
  8   def []=(key, val)
  9     @hash_ary.each do |e|
 10       e[key]=val if e.key?(key)
 11     end
 12     @hash_ary << Hash[key, val]
 13   end
 14
 15   def [](key)
 16     @hash_ary.each do |e|
 17       return e[key] if e.key?(key)
 18     end
 19     return nil
 20   end
 21
 22   def each
 23     @hash_ary.each do |e|
 24       ary = e.to_a.flatten
 25       yield(ary[0], ary[1])
 26     end
 27   end
 28 end
irb(main):096:0> load 'orderd_hash.rb'
=> true
irb(main):097:0> h = OrderdHash.new
=> #<OrderdHash:0xb7f72544 @hash_ary=[]>
irb(main):098:0> h["one"] = 1
=> 1
irb(main):099:0> h["two"] = 2
=> 2
irb(main):100:0> h["three"] = 3
=> 3
irb(main):101:0> h["four"] = 4
=> 4
irb(main):102:0> h["five"] = 5
=> 5
irb(main):103:0> h.each do |k,v|
irb(main):104:1*  puts "key is #{k} and value is #{v}"
irb(main):105:1> end
key is one and value is 1
key is two and value is 2
key is three and value is 3
key is four and value is 4
key is five and value is 5
=> [{"one"=>1}, {"two"=>2}, {"three"=>3}, {"four"=>4}, {"five"=>5}]