Ruby/Hash/Hash.new

Материал из Wiki.crossplatform.ru

Версия от 17:57, 13 сентября 2010; ViGOur (Обсуждение | вклад)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Содержание

access any key in a hash that has a default value

if the key or value doesn"t exist, accessing the hash will return the default value:
months = Hash.new( "month" )
months[0]
# or:
months[72]
# or:
months[234]



Creating Hashes

# You can create an empty hash with the new class method.
months = Hash.new



Hash.new with block logic

p h = Hash.new { |hash, key| (key.respond_to? :to_str) ? "nope" : nil }
p h[1]                                           # => nil
p h["do"]                   # => "nope"



Hash with =>

myHash = Hash[ :name => "Jack", :partner => "Jane", :employee => "Joe" =>:location,"London", :year => 1843 ]



Test how big it is with length or size

months = Hash.new
months.length
months.size # => 0



This lazily initialized hash maps integers to their factorials

fact = Hash.new {|h,k| h[k] = if k > 1: k*h[k-1] else 1 end }
p fact      # {}: it starts off empty
p fact[4]   # 24: 4! is 24
p fact      # {1=>1, 2=>2, 3=>6, 4=>24}: the hash now has entries



use new to create a hash with a default value which is otherwise just nil

months = Hash.new( "month" )
# or like this:
months = Hash.new "month"



You can test to see if a hash is empty with empty?

months = Hash.new
months.empty? # => true