h1 = Hash.new #默认值为nil h2 = Hash.new(“This is my first hash instance”) #默认值为” This is my first hash instance”:
h2["one"] = "北京" h2["two"] = "上海" h2["three"] = "深圳" h2["four"] = "广州"
h2 = {
"one" => "北京",
"two" =>"上海",
"three" =>"深圳",
"four" =>"广州"
}
puts h2[“one”] #=>”北京”
puts h1.default
h1.default += “This is set value method”
h3 = h2
h3[“one”] = “西安”
puts h h2[“one”] #=>”西安”
copy
h4 = h2.clone
h4[“one”] = “大连”
puts h2[“one”] #=>”西安”(i.e. 值没有修改)
def sorted_hash(aHash)
return aHash.sort{
|a,b| a.to_s <=> b.to_s
}
End
h1 = {1=>'one', 2=>'two', 3=> 'three'}
h2 = {6=>'six', 5=>'five', 4=> 'four'}
h3 = {'one'=>'A', 'two'=>'B','three'=>'C'}
h4 = h1.merge(h2) #合并hash
h5 = h1.merge(h3)
def sorted_hash(aHash)
return aHash.sort{|a,b| a.to_s <=> b.to_s }
end
p(h4)
p(h4.sort)
p(h5)
p(sorted_hash(h5))
{5=>"five", 6=>"six", 1=>"one", 2=>"two", 3=>"three", 4=>"four"}
[[1, "one"], [2, "two"], [3, "three"], [4, "four"], [5, "five"], [6, "six"]]
{"two"=>"B", "three"=>"C", 1=>"one", 2=>"two", "one"=>"A", 3=>"three"}
[[1, "one"], [2, "two"], [3, "three"], ["one", "A"], ["three", "C"], ["two", "B"]]
|
方法 |
说明 |
| size() | 返回Hash对象的长度 |
| length() | 返回Hash对象的长度 |
| include?(key) | 判断指定的Hash对象是否包含指定的key |
| has_key?(key) | 判断指定的Hash对象是否包含指定的key |
| delete(key) | 删除Hash对象中指定key的对应元素 |
| keys() | 返回由Hash对象中全部key组成的数组 |
| values() | 返回由Hash对象中全部value组成的数组 |
student = {
"name" => "Steve",
"age" => 22,
"Gender" => "male"
}
p student.keys #=> ["name", "Gender", "age"]
p student.values #=> ["Steve", "male", 22]
puts student.include?("age") #=> true
puts student.size #=> 3
student.delete("Gender")
puts student.has_key?("Gender") #=>false
puts student.size #=>2
h1 = {1=>'one', 2=>'two', 3=> 'three',4=> 'four'}
h2 = {1=>'one', 3=>'two', 4=> 'four',5=> 'five'}
p( h1.keys & h2.keys )
p( h1.values & h2.values )
p( h1.keys+h2.keys )
p( h1.values-h2.values )
p( (h1.keys << h2.keys) )
p( (h1.keys << h2.keys).flatten)
[1, 3, 4] ["one", "two", "four"] [1, 2, 3, 4, 5, 1, 3, 4] ["three"] [1, 2, 3, 4, [5, 1, 3, 4]] [1, 2, 3, 4, 5, 1, 3, 4]
a=[1,2,3] b=[4,5,6] p(a+b) p(a<<b)
[1, 2, 3, 4, 5, 6] [1, 2, 3, [4, 5, 6]] #[1, 2, 3, [4, 5, 6]].flatten =>[1, 2, 3, 4, 5, 6]
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有