我正在审核Rails项目中的一段代码,我遇到了tap
方法。它做了什么?
此外,如果有人能帮助我理解其余代码的作用,那就太棒了:
def self.properties_container_to_object properties_container
{}.tap do |obj|
obj['vid'] = properties_container['vid'] if properties_container['vid']
obj['canonical-vid'] = properties_container['canonical-vid'] if properties_container['canonical-vid']
properties_container['properties'].each_pair do |name, property_hash|
obj[name] = property_hash['value']
end
end
end
谢谢!
答案 0 :(得分:13)
.tap
来到"对一系列方法中的中间结果执行操作" (引用ruby-doc)。
换句话说,object.tap
允许您操纵object
并在阻止后返回它:
{}.tap{ |hash| hash[:video] = 'Batmaaaaan' }
# => return the hash itself with the key/value video equal to 'Batmaaaaan'
所以你可以用.tap
来做这样的事情:
{}.tap{ |h| h[:video] = 'Batmaaan' }[:video]
# => returns "Batmaaan"
相当于:
h = {}
h[:video] = 'Batmaaan'
return h[:video]
更好的例子:
user = User.new.tap{ |u| u.generate_dependent_stuff }
# user is equal to the User's instance, not equal to the result of `u.generate_dependent_stuff`
您的代码:
def self.properties_container_to_object(properties_container)
{}.tap do |obj|
obj['vid'] = properties_container['vid'] if properties_container['vid']
obj['canonical-vid'] = properties_container['canonical-vid'] if properties_container['canonical-vid']
properties_container['properties'].each_pair do |name, property_hash|
obj[name] = property_hash['value']
end
end
end
返回填充.tap
块
您的代码的长版本将是:
def self.properties_container_to_object(properties_container)
hash = {}
hash['vid'] = properties_container['vid'] if properties_container['vid']
hash['canonical-vid'] = properties_container['canonical-vid'] if properties_container['canonical-vid']
properties_container['properties'].each_pair do |name, property_hash|
hash[name] = property_hash['value']
end
hash
end
答案 1 :(得分:0)
点击是来自对象类的Ruby方法。
此方法为块生成 x ,然后返回x。此方法用于“挖掘”方法链,以对链中的中间结果执行操作。