Ruby哈希函数和哈希函数排序
【摘要】 笔者主要介绍Ruby哈希函数和哈希函数的排序
h1 = Hash.new
h2 = Hash.new("Some kind of ring")
h2['treasure1'] = 'Silver ring'
h2['treasure2'] = 'Gold ring'
h2['treasure3'] = 'Ruby ring'
h2['treasure4'] = 'Sapphire ring'
x1 = Hash.new('my Xobject')
h2[x1] = 'Diamond ring'
h1 = { 'room1'=>'The Treasure Room',
'room2'=>'The Throne Room',
'loc1'=>'A Forest Glade',
'loc2'=>'A Mountain Stream' }
puts(h1['room2']) #=> 'The Throne Room'
puts(p(h1['unknown_room'])) #=> nil
puts(p(h2['unknown_treasure'])) #=> 'Some kind of ring'
puts(p(h1.default))
h1.default = 'A mysterious place'
puts(p(h1.default))
The Throne Room
nil
"Some kind of ring"
Some kind of ring
nil
"A mysterious place"
A mysterious place
h4 = h1
h4['room1']='A new Room'
puts(h1['room1']) #=> 'A new Room'
h5 = h1.clone
h5['room1'] = 'An even newer Room'
puts(h1['room1']) #=> 'A new room' (i.e., its value is unchanged)
A new Room
A new Room
h = {2=>"two", 1=>"one", 4=>"four" }
p( h )
h[3] = "three"
p( h )
h2 = {"one"=>1, 2=>"two", 4.5=>"four" }
p (h2)
{2=>"two", 1=>"one", 4=>"four"}
{2=>"two", 1=>"one", 4=>"four", 3=>"three"}
{"one"=>1, 2=>"two", 4.5=>"four"}
def sorted_hash( aHash )
return aHash.sort{
|a,b|
a.to_s <=> b.to_s
}
end
h = {2=>"two", 1=>"one", 4=>"four" }
p( sorted_hash(h ))
h[3] = "three"
p( sorted_hash(h ) )
h2 = {"one"=>1, 2=>"two", 4.5=>"four" }
p (sorted_hash(h2 ))
[[1, "one"], [2, "two"], [4, "four"]]
[[1, "one"], [2, "two"], [3, "three"], [4, "four"]]
[["one", 1], [2, "two"], [4.5, "four"]]
开发环境:Rubymine
The book of Ruby----A hands-on guide for the Adventurous---[美]Huw Collingbourne---no starch press
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区),文章链接,文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件至:cloudbbs@huaweicloud.com进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容。
- 点赞
- 收藏
- 关注作者
评论(0)