试图在这里理解这个问题。我创建了我自己的散列#合并名为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
任何帮助将不胜感激。谢谢!