散列表数组是对象的集合,散列表也是。然而,散列表有不同的存储格式,以及在集合中定义每个对象的不同方法。散列表中的对象不在列表中给定位置,而是给定一个指定对象的键(key)。散列表更像字典,而不像列表,因为它没有确定的顺序,只有键和值之间的简单链接。下面是个基本的散列表,其中有两个元素:dictionary = {‘cat’=> 'feline animal',‘dog’=> 'canine animal'}irb(main):029:0> dictionary = {'cat' => 'feline animal','dog' => 'canine animal'}=> {"cat"=>"feline animal", "dog"=>"canine animal"}irb(main):030:0> puts dictionary.size   \\ 检查一下其长度2=> nilirb(main):031:0> puts dictionary['cat']  \\检索键‘cat’的值feline animal=> nilirb(main):033:0>  dictionary['cat'] = 'female animal' \\更改键‘cat’的值=> "female animal"irb(main):034:0> puts dictionary['cat']    \\输出修改后的键‘cat’的值female animal=> nil散列表的基本方法对于数组,可以使用each方法实现在数组元素中迭代,对于散列表也可以进行此项操作,但由于散列表每个元素都用键,因此迭代响应的顺序不固定:irb(main):001:0> x = { "a" => 1, "b" => 2}=> {"b"=>2, "a"=>1}irb(main):002:0> x.each { |key, value| puts "#{key} equals #{value}" }b equals 2a equals 1=> {"b"=>2, "a"=>1}散列表的each迭代子方法是将两个参数传递给代码块:第一个是键,第二个是键所对应的值,上述的例子是把它们赋给名为key和value的变量,并用字符串插写的方法,将其内容显示到屏幕上。检索键Ruby提供了keys方法,可以让用户很容易查看任何散列表的键:irb(main):003:0> x = { "a" => 1, "b" => 2, "c" => 3}=> {"c"=>3, "b"=>2, "a"=>1}irb(main):004:0> puts x.keys.inspect["c", "b", "a"]=> nil删除散列表中的元素删除散列表元素很简单,使用delete方法即可,如:irb(main):007:0> x = { "a" => 1, "b" => 2, "c" => 3}=> {"c"=>3, "b"=>2, "a"=>1}irb(main):008:0> x.delete("a")=> 1irb(main):009:0> puts x.inspect{"c"=>3, "b"=>2}=> nil如果我们想删除符合条件的所有元素,那就使用delete_if 方法,如:irb(main):011:0> x = { "a" => 120, "c" => 35, "d" => 49 }=> {"d"=>49, "c"=>35, "a"=>120}irb(main):012:0> x.delete_if {|key, value| value=> {"a"=>120}irb(main):013:0> puts x.inspect{"a"=>120}=> nil
09-04 12:23