1月4日编程基础hash

早上git加星了webapp的教程

> h = Hash.new('Go Fishing')       => {}  // 创建一个空hash,设定"Go Fishing"为默认的值。 
> h['c']                                        => "Go Fishing" 

> 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_key?(key) → true or false

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)

def find_max(hash)
  arr = hash.values
  arr_max = arr.max
  re_string = ''
  hash.each do |key, value|
    if value == arr_max
        re_string = re_string + key.to_s + " "
    end
  end
  return re_string
end
h = {
  "a" => 71,
  "b" => 38,
  "c" => 21,
  "d" => 80,
  "e" => 80
}
answer = find_max(h)
puts "有最大 value 的是 #{answer}" 

 题目 26

# 给定一个数组包含 Hash,请过滤和排序
arr = [
  { "name" => "Peter", "age" => 30 },
  { "name" => "John", "age" => 15 },
  { "name" => "David", "age" => 45 },
  { "name" => "Steven", "age" => 22 },
  { "name" => "Vincent", "age" => 6 },
]
# 找出成年人,生成新的数组
adult = []
arr.each do |i|
  if i["age"] > 18  
    adult << i
  end
end
# 排序
result = adult.sort_by{|i| i["age"] }   //用到了sort_by{}

https://ruby-doc.org/core-2.4.1/Enumerable.html#method-i-sort_by 

puts "所有成年人,并由小到大:#{result}"
原文地址:https://www.cnblogs.com/chentianwei/p/8191372.html