数组和Hash对象是统一的,数组只是Hash对象的一种表现形式,Hash对象里包含的元素的key是任意的,而数组里所包含的key是连续的,而且只能够使整数,在同一hash中,索引键必须唯一
Hash对象里的元素都是由两部分组成:key和value两个部分
Hash对象是由一些列在花括号里面的key-value对组成,多个key-value对之间以英文逗号隔开,key和value之间由"=>"隔开,最后一个逗号会被省略
a={"zhansa"=>40,"lisi"=>20,"wangwu"=>25}
p a;
p a["zhansa"]
p a["lisi"]
结果
{"wangwu"=>25, "lisi"=>20, "zhansa"=>40}
40
20
my_hash = Hash.new
puts "Hash对象的长度"+my_hash.size.to_s
my_hash["Java"]=5
p my_hash
my_hash["Ruby"]="aaaa"
p my_hash
输出结果
Hash对象的长度0
{"Java"=>5}
{"Ruby"=>"aaaa", "Java"=>5}
Hash对象的常用方法
length()/size()
delete(key)
include?(key)\has_key?(key)\key?\member? 判断指定的Hash对象是否包含特定的key
keys()
values()
b={"zhansa"=>40,"lisi"=>20,"wangwu"=>25}
p b.length().to_s
p b.include?("zhansa")
p b.keys
p b.values()
输出值
"3"
true
["wangwu", "lisi", "zhansa"]
[25, 20, 40]
Hash对象的迭代
Hash对象支持如下4个常用迭代
each:迭代输出Hash对象里全部项(包括key和value)
each_key 迭代输出Hash对象里全部key
each_pair 迭代输出Hash对象里全部key-value对
each_value 迭代输出Hash对象里全部value
b={"zhansa"=>40,"lisi"=>20,"wangwu"=>25}
b.each do |key,value|
puts "key:"+key+",value:"+value.to_s
end
b.each_key do |key|
puts "key:"+key
end
b.each_value do |value|
puts "value:"+value.to_s
end
b.each_pair do |key,value|
puts "key:"+key+",value:"+value.to_s
end
输出结果
key:wangwu,value:25
key:lisi,value:20
key:zhansa,value:40
key:wangwu
key:lisi
key:zhansa
value:25
value:20
value:40
key:wangwu,value:25
key:lisi,value:20
key:zhansa,value:40