Ruby中关于hash的基本使用方法

本文主要给大家讲解hash的索引运算表达式、哈希表的比较及使用方法。下面就来看看学习ruby(http://www.maiziedu.com/course/ruby-px/)编程语言时对hash的理解,希望能帮助正在学习ruby的同学。 
哈希表:哈希表(ash)是使用某一任意对象作为键来对应其他对象的容器对象。 
eg1: 
month_to_ordinal = { 
"Jan" => 1, "Feb" => 2, "Mar" => 3, "Apr" => 4, "May" => 5, "Jun" => 6, 
"Jul" => 7, "Aug" => 8, "Sep" => 9, "Oct" => 10, "Nov" => 11, "Dec" => 12 

p month_to_ordinal [ "Aug" ]         #=>8 
p month_to_ordinal [ "Jun" ]          #=>6 
索引运算表达式:对哈希表索引要比数组简单,就是通过传递被作为键的对象来返回对应的值。 
eg1: 
book_to_author = { 
"Ruby in Nutshell" => "Flanagan", 
"Programming Ruby" => "Thomas", 
"AWDwR" => "Thomas" 

p book_to_author [ "Programming Ruby" ]           #=>Thomas 
p book_to_author [ "Programming Perl" ]            #=>nil 
p book_to_author [ "The Ruby Way" ] = "Fulton"       #=>Fulton 
哈希表的比较:Hash对象之间,对象中所对应的元素的键和值都相等才相等。 
eg1: 
hash1 = { "a" => 1, "b" => 2 } 
hash2 = { "a" => 1, "b" => 2 } 
p hash1 == hash2                    #=>true 
p hash1 == { "a" =>9, "b" => 2 }         #=>false 
各种各样的方法:所有的Hash表都是Hash的实例,Hash类中也提供了大量的方法。 
eg1: 
book_to_author . each do | book, author | 
puts "#{book} by #{author}" 
end 


p book_to_author . map { | book, author | 
"#{book} by #{author}" 

你可能感兴趣的:(编程语言,表达式)