Вы находитесь на странице: 1из 3

# 4.0 Introduction to Ruby Hashes Creating a Hash =============== A Hash is a collection of key-value pairs.

You retrieve or create a new entry in a Hash by referring to its key. Hashes are also called 'associative arrays', 'd ictionary', 'HashMap' etc. in other languages A blank hash can be declared using two curly braces {}. Here is an example of a Hash in Ruby: student_ages = { "Jack" => 10, "Jill" => 12, "Bob" => 14 } The names (Jack, Jill, Bob) are the 'keys', and 10, 12 and 14 are the correspond ing values. Now try creating a simple hash with the following keys and values: Ramen = 3 Dal Makhani = 4 Tea = 2 restaurant_menu = { "Ramen" => 3, "Dal Makhani" => 4, "Tea" => 2 } Fetch values from a Hash ======================== You can retrieve values from a Hash object using [] operator. The key of the req uired value should be enclosed within these square brackets. Now try finding the price of a Ramen from the restaurant_menu hash: write the na me of the object, follow it with a square bracket, and place the key inside the brackets. In this case the key is a string so enclose the key in quotes. restaurant_menu['Ramen'] That was very simple, wasn't it? One small step at a time! Modifying a Hash Once you've created a Hash object, you would want to add new key-value pairs as well as modify existing values. Here is how you would set the price of a "Ramen" in the restaurant_menu hash: restaurant_menu["Ramen"] = 3 In fact, you can create a blank hash and add all the values later. Now why don't you try assigning the following values to an empty hash? Dal Makhani: 4.5 Tea: 2 restaurant_menu = {}

restaurant_menu['Ramen'] = 3 restaurant_menu['Dal Makhani'] = 4.5 restaurant_menu['Tea'] = 2 # 4.1 Hashes, in and out. Iterating over a Hash ===================== You can use the each method to iterate over all the elements in a Hash. However unlike Array#each, when you iterate over a Hash using each, it passes two values to the block: the key and the value of each element. Let us see how we can use the each method to display the restaurant menu. Example Code: restaurant_menu = { "Ramen" => 3, "Dal Makhani" => 4, "Coffee" => 2 } restaurant_menu.each do | item, price | puts "#{item}: $#{price}" end The restaurant is doing well, but it is forced to raise prices due to increasing costs. Use the each method to increase the price of all the items in the restau rant_menu by 10%. Remember: in the previous example we only displayed the keys and values of each item in the hash. But in this exercise, you have to modify the hash and increase the value of each item. restaurant_menu = { "Ramen" => 3, "Dal Makhani" => 4, "Coffee" => 2 } restaurant_menu.each do | item, price | restaurant_menu[item] = 1.1 * price end Extracting the keys and values from a Hash ========================================== Every Hash object has two methods: keys and values. The keys method returns an a rray of all the keys in the Hash. Similarly values returns an array of just the values. Try getting an array of all the keys in the restaurant_menu hash: restaurant_menu = { "Ramen" => 3, "Dal Makhani" => 4, "Coffee" => 2 } restaurant_menu.keys Newer, faster. ============== There are some little-known shortcuts for creating new hashes. They all provide a slightly different convenience. The latter two generate a hash directly from p re-existing key-value pairs. The first simply sets a default value for all eleme nts in the hash. Let's take a look at that first. Example Code: normal = Hash.new was_not_there = normal[:zig] puts "Wasn't there:" p was_not_there usually_brown = Hash.new("brown") pretending_to_be_there = usually_brown[:zig]

puts "Pretending to be there:" p pretending_to_be_there As you can see, where a "normal" hash always returns nil by default, specifying a default in the Hash constructor will always return your custom default for any failed lookups on that hash instance. The other two shortcuts actually use the Hash class's convenience method: Hash:: []. They're fairly straight-forward. The first takes a flat list of parameters, arranged in pairs. The second takes just one parameter: an array containing arra ys which are themselves key-value pairs. Whew! That's a mouthful. Let's try the first form: Example Code: chuck_norris = Hash[:punch, 99, :kick, 98, :stops_bullets_with_hands, true] p chuck_norris Cool. And easy! You have to now use the second form the "new hash" shortcut in t his exercise. Again, it takes an array of key-value pairs. These key-value pairs will just be 2-element arrays. I'll give you the key-value pairs to start with. Your objective is to build a Hash out of this array. def artax a = [:punch, 0] b = [:kick, 72] c = [:stops_bullets_with_hands, false] # key_value_pairs = [a, b, c] key_value_pairs = [] key_value_pairs << a << b << c Hash[key_value_pairs] end p artax

Вам также может понравиться