試圖在這裏理解這個問題。我創建了我自己的散列#合併名爲hash#my_merge的可以在proc中使用的版本。我想知道是什麼做的:試圖理解哈希的實現#與Procs合併
self.each do |k,v|
newhash[k]=hash[k] ? prc.call(k,v,hash[k]): v
end
它看起來像一個三元操作,但newhash [K] =散列[K]是不是一個真正的/虛假陳述?提示和問題的其餘部分如下:
class Hash
# Hash#merge takes a proc that accepts three arguments: a key and the two
# corresponding values in the hashes being merged. Hash#merge then sets that
# key to the return value of the proc in a new hash. If no proc is given,
# Hash#merge simply merges the two hashes.
#
# Write a method with the functionality of Hash#merge. Your Hash#my_merge
method
# should optionally take a proc as an argument and return a new hash. If a
proc
# is not given, your method should provide default merging behavior. Do not
use
# Hash#merge in your method.
def my_merge(hash, &prc)
prc ||=Proc.new{|k,oldval,newval|}
newhash=Hash.new
self.each do |k,v|
newhash[k]=hash[k] ? prc.call(k,v,hash[k]): v
end
hash.each do |k,v|
newhash[k]=v if newhash[k].nil?
end
newhash
end
end
任何幫助將不勝感激。謝謝!