Ruby学习笔记--散列(哈希)

做完keep有点晚了,不过还是要学习。先上今天学的代码:

#create a mapping of state to abbreviation
states = {
    'Oregon' => 'OR',
    'Florida' => 'FL',
    'California' =>'CA',
    'New York' => 'NY',
    'Michigan' => 'MI'
}

#create a basic set of states and some cities in them
cities = {
    'CA' => 'San francisco',
    'MI' => 'Detroit',
    'FL' => 'Jacksonville'
}

#add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'

#puts out some cities
puts '-' * 10
puts "NY State has: #{cities['NY']}"
puts "OR State has: #{cities['OR']}"

#puts some states
puts '-' * 10
puts "Michigan's abbreviation is: #{states['Michigan']}"
puts "Florida's abbreviation is: #{states['Florida']}"

#do it by using the state then cities dict
puts '-' * 10
puts "Michigan has: #{cities[states['Michigan']]}"
puts "Florida has: #{cities[states['Florida']]}"

#puts every state abbreviation
puts '-' * 10
states.each do |state, abbrev|
    puts "#{state} is abbreviated #{abbrev}"
end

#puts every city in state
puts '-' * 10
cities.each do |abbrev, city|
    puts "#{abbrev} has the city #{city}"
end

#now do both at the same time
puts '-' * 10
states.each do |state, abbrev|
    city = cities[abbrev]
    puts "#{state} is abbreviated #{abbrev} and has city #{city}"
end

puts '-' * 10
#by default ruby says "nil" when something isn't in there
state = states['Texas']

if !state
    puts "Sorry, No Texas."
end

#default values using ||= with the nil result
city = cities['TX']
city ||= 'Does Not Exist'
puts "The city for the state 'TX' is: #{city}" 

当然这段代码不是我的原创,我才不会写这么麻烦的代码,这是教材第39个练习。
这段代码先读,然后在脑子里跑一遍,居然跑通了。说明我对散列比较了解了。
然后搬到电脑上,顺利跑通。

可以先做一个简单的类比,根据我的理解,散列就是一个数据库,可以把你想要的任何东西放在里头,甚至可以是非常复杂的结构。回头我尝试把股票信息塞里头,嗯,和数组有什么区别呢?
数组的关联性比较单调一些,只能用索引进行关联,而哈希的关联就非常复杂,非常酷了,可以将任意东西进行关联。
感觉普通的应用是没必要用数据库了啊... ...
今天的故事构思了差不多,明天中午写出来。

你可能感兴趣的:(Ruby学习笔记--散列(哈希))