Ruby/Hash/Hash Keys

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

Перейти к: навигация, поиск

Содержание

Extract data from the hash by using its keys.

money_I_am_owed = {"Dan" => "$1,000,000", "Mike" => "$500,000"}
puts money_I_am_owed["Dan"]



Get all keys from a hash

hash = {1 => 2, 2 => 2, 3 => 10}
p hash.keys                                    # => [1, 2, 3]



Hash as a key

key = {:a=>1}      # This hash will be a key in another hash!
p h = { key => 2 }   # This hash has a mutable key
p h[key]             # => 2: get value associated with key
p key.clear          # Mutate the key
p h[key]             # => nil: no value found for mutated key
p h.rehash           # Fix up the hash after mutation
p h[key]             # => 2: now the value is found again



Join hash keys together

hash = { "key1" => "val1", "key2" => "val2" }
string = ""
hash.each { |k,v| string << k << " is " << v << "\n" }
puts hash.keys.join("\n") + "\n"
puts string



Retrieving Keys

x = { "a" => 1, "b" => 2, "c" => 3 }
puts x.keys.inspect



Return an array containing all the keys in a hash with keys:

zip = { 1 => "One", 2 => "Two", 3 => "Three",
4 => "Four", 5 => "Five", 6 => "Six", 7 =>
"Seven", 8 => "Eight", 9 => "Eight" }
zip.keys # => [8, 3, 6, 9, 5, 2, 1, 4, 7]



RuntimeError: hash modified during iteration

1.upto(100) { |x| hash[x] = true }
hash.keys { |k| hash[k * 2] = true }



Searching a Hash with Regular Expressions

h = { "apple tree" => "plant", "ficus" => "plant",
      "shrew" => "animal", "plesiosaur" => "animal" }
h.keys.grep /p/
# => ["apple tree", "plesiosaur"]



Time value key

require "time"
click_counts = {}
1.upto(30) { |i| click_counts[Time.parse("2006-09-#{i}")] = 400 + rand(700) }
p click_counts



Use number as hash key

money = {1 => "$1,000,000", 2 => "$500,000"}
puts money[1]



What if a key does not exist

empty = {}
empty["one"]   # nil