Ruby/Hash/Hash Creation
Материал из Wiki.crossplatform.ru
A hash ( associative array or a dictionary) is an array holding a collection of data,
# you can index it using text strings as well as numbers. # To create a hash, you use curly braces, { and }, not square braces ([]) as with arrays. money = {"Dan" => "$1,000,000", "Mike" => "$500,000"} # "Dan" is a hash key # "$1,000,000" is the value. # The => operator separates the keys from the values.
Create a hash with default value
h = Hash.new("Go Fish") h["a"] = 100 h["b"] = 200 h["a"] 100 h["c"] # The following alters the single default object h["c"].upcase! h["d"] h.keys
creates a new default object each time
h = Hash.new {|hash, key| hash[key] = "Go Fish: #{key}" } h["c"] h["c"].upcase! h["d"] h.keys
Creating a Hash with a Default Value
h = Hash.new("nope") p h[1] # => "nope" p h["do you have this string?"] # => "nope"
Element Assignment
h = { "a" => 100, "b" => 200 } h["a"] = 9 h["c"] = 4 puts h
Hashes use braces instead of brackets to let the Ruby interpreter know what is being created.
fruit = { :apple => "fruit", :orange => "fruit", :squash => "vegetable" } puts fruit[:apple] fruit[:corn] = "vegetable" puts fruit[:corn]
Hash has a class method [], which is called in either one of two ways: with a comma separating the pairs
myHash = Hash[ :name, "Jack", :partner, "Jane", :employee, "Joe", :location, "London", :year, 1843 ]
Instead of integers, you could use strings for the keys
month_a = { "jan" => "January", "feb" => "February", "mar" => "March", "apr"
The hash definition is enclosed in curly braces, whereas an array is defined in square brackets.
Each value is associated (=>) with a key. One of the ways you can access the values in a hash is by their keys. pacific = { "WA" => "Washington", "OR" => "Oregon", "CA" => "California" } pacific["OR"] # => "Oregon"
Using Hashes
pizza = {"first_topping" => "pepperoni", "second_topping" => "sausage"} p pizza["first_topping"] p pizza p pizza.length receipts = {"day_one" => 5.03, "day_two" => 15_003.00} p receipts["day_one"] p receipts["day_two"]
you can store numbers in hashes
receipts = {"day_one" => 5.03, "day_two" => 15_003.00} puts receipts["day_one"] puts receipts["day_two"]