Ruby编程之哈希函数介绍和数组合并与拼接
【摘要】 本文主要介绍了Ruby编程之哈希函数介绍和数组合并与拼接
h1 = {
'room1'=>'The Treasure Room',
'room2'=>'The Throne Room',
'loc1'=>'A Forest Glade',
'loc2'=>'A Mountain Stream'
}
h2 = {1=>'one', 2=>'two', 3=> 'three'}
h1['room1'] = 'You have wandered into a dark room'
h1.delete('loc2')
p(h1)
#=> {"room1"=>"You have wandered into a dark room",
#=> "room2"=>"The Throne Room",
#=> "loc1"=>"A Forest Glade"}
p(h1.has_key?('loc2')) #=> false
p(h2.has_value?("two")) #=>true
p(h2.invert) #=> {"one"=>1, "two"=>2, "three"=>3}
p(h2.keys) #=>[1, 2, 3]
p(h2.values) #=>["one", "two", "three"]
p(h2.key("two")) # use this Ruby 1.9
{"room1"=>"You have wandered into a dark room", "room2"=>"The Throne Room", "loc1"=>"A Forest Glade"}
false
true
{"one"=>1, "two"=>2, "three"=>3}
[1, 2, 3]
["one", "two", "three"]
2
h1 = {'key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3', 'key4'=>'val4'}
h2 = {'key1'=>'val1', 'KEY_TWO'=>'val2', 'key3'=>'VALUE_3', 'key4'=>'val4'}
p( h1.keys & h2.keys ) # set intersection (keys)
#=> ["key1", "key3", "key4"]
p( h1.values & h2.values ) # set intersection (values)
#=> ["val1", "val2", "val4"]
p( h1.keys+h2.keys ) # concatenation
#=> [ "key1", "key2", "key3", "key4", "key1", "key3", "key4", "KEY_TWO"]
p( h1.values-h2.values ) # difference
#=> ["val3"]
p( (h1.keys << h2.keys) ) # append
#=> ["key1", "key2", "key3", "key4", ["key1", "key3", "key4", "KEY_TWO"]]
p( (h1.keys << h2.keys).flatten.reverse ) # 'un-nest' arrays and reverse
#=> ["KEY_TWO", "key4", "key3", "key1", "key4", "key3", "key2", "key1"]
["key1", "key3", "key4"]
["val1", "val2", "val4"]
["key1", "key2", "key3", "key4", "key1", "KEY_TWO", "key3", "key4"]
["val3"]
["key1", "key2", "key3", "key4", ["key1", "KEY_TWO", "key3", "key4"]]
["key4", "key3", "KEY_TWO", "key1", "key4", "key3", "key2", "key1"]
a =[1,2,3]
b =[4,5,6]
c = a + b #=> c=[1, 2, 3, 4, 5, 6] a=[1, 2, 3]
a << b #=> a=[1, 2, 3, [4, 5, 6]]
p(c)
p(a)
[1, 2, 3, 4, 5, 6]
[1, 2, 3, [4, 5, 6]]
a=[1, 2, 3, [4, 5, 6]]
p(a.flatten) #=> [1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
开发环境:Rubymine
The book of Ruby----A hands-on guide for the Adventurous---[美]Huw Collingbourne---no starch press
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区),文章链接,文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件至:cloudbbs@huaweicloud.com进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容。
- 点赞
- 收藏
- 关注作者
评论(0)