早上git加星了webapp的教程
> h => {} //但并没有存入hash。仍然是空的。
h = Hash.new { |hash, key| hash[key] = "Go Fish: #{key}" }
创建一个空hash,设置了默认的value值,如:
h["c"] #=> "Go Fish: c"
hash存入key,value对儿,不再为空。
hash的Methods中有 比较的operation. < , <= , ==, > ,>=.
clear -> hsh: Removes all key-value pairs from hsh.
values → array :
Returns a new array populated with the values from hsh. 同理 h.keys 回传一个数组包含所以keys.
h = { "a" => 100, "b" => 200, "c" => 300 } h.keys #=> ['a', 'b', 'c']
h.values #=> [100, 200, 300]
另外: h.valuse_at('a', 'b') #=> [100, 200] 这是指定一组keys,回传一组【values】
Lenght -> integer
h = { "d" => 100, "a" => 200, "v" => 300, "e" => 400 }
h.length #=> 4
h.delete("a") #=> 200
h.length #=> 3
store(key, value) -> value
Associates the value given by value with the key given by key.
h = { "a" => 100, "b" => 200 } h["a"] = 9 h["c"] = 4 //本来没有,于是新增一对kv值。 h #=> {"a"=>9, "b"=>200, "c"=>4} h.store("d", 42) #=> 42 h #=> {"a"=>9, "b"=>200, "c"=>4, "d"=>42}
merge(other_hash) → new_hash
merge(other_hash){|key, oldval, newval| block} → new_hash
Returns a new hash containing the contents of other_hash and the contents of hsh. If no block is specified, the value for entries with duplicate keys will be that of other_hash.
Otherwise the value for each duplicate key is determined by calling the block with the key, its value in hsh and its value in other_hash.
For example:
h1 = { "a" => 100, "b" => 200 } h2 = { "b" => 254, "c" => 300 } h1.merge(h2) #=> {"a"=>100, "b"=>254, "c"=>300} h1.merge(h2){|key, oldval, newval| (newval - oldval)*2 } #=> {"a"=>100, "b"=>108, "c"=>300} h1 #=> {"a"=>100, "b"=>200}
has_value?(value) → true or false
h = { "a" => 100, "b" => 200 } h.has_key?("a") #=> true
h.value?(100) #=> true
h.value?(999) #=> false
题目 23
给定一散列 Hash,输出有最大值(value)的键(key)
题目 26
https://ruby-doc.org/core-2.4.1/Enumerable.html#method-i-sort_by