Rubyのハッシュ
[履歴] (2013/07/14 03:54:37)
最近の投稿
注目の記事

概要

RubyのハッシュはPerlの無名ハッシュと似ています。

sample.rb

hash = {
  "alice" => 1,
  "bob" => 2,
}
p hash["alice"]

hash["alice"] *= 2
p hash["alice"]

出力例

$ ruby sample.rb 
1
2

Keyの部分を以下のように記述することもできます。

hash = {
  alice: 10,
  bob: 20,
}
p hash[:alice]

比較

配列の場合と同様にハッシュ同士の比較は全要素が等しい場合にtrueを返します。

便利なメソッド

配列の場合と同様にsizeなどがあります。また、Perlと同じようにkeysメソッドがあります。

イテレータ

sample.rb

hash = {
  alice: 10,
  bob: 20,
}

hash.each do |key,val|
  puts "#{key} is #{val} years old."
end

出力例

$ ruby sample.rb 
alice is 10 years old.
bob is 20 years old.

全要素を一度に操作

配列の場合と同様にmapが実装されています。

sample.rb

hash = {
  alice: 10,
  bob: 20,
}
array = hash.map{|key,val| "#{key} is #{val} years old."}
p array

出力例

$ ruby sample.rb 
["alice is 10 years old.", "bob is 20 years old."]
関連ページ