Ruby Tips!

RubyのTipsを紹介します

順序付きのハッシュを利用する

Ruby 1.9のハッシュは順序付きで、要素を挿入した順序に取り出すことができる。

hash = {}
hash[:a] = 1
hash[:b] = 2
hash[:c] = 3
hash.each{|k, v|
  puts k.to_s + v.to_s #=> a1 b2 c3
}

Ruby 1.8ではハッシュは順序を持たないので、Ruby 1.9のようにはいかない。順序付きのハッシュを利用したければ、自分で実装するか、外部のライブラリが必要だ。

幸いActiveSupportには順序付きハッシュを実装したOrderedHashが用意されている。ActiveSupportはGemでインストールできる。

gem install activesupport

OrderedHashは順序付きである以外はハッシュと同様に利用できる。

require 'active_support'

hash = ActiveSupport::OrderedHash.new
hash = {}
hash[:a] = 1
hash[:b] = 2
hash[:c] = 3
hash.each{|k, v|
  puts k.to_s + v.to_s #=> a1 b2 c3
}