了解Ruby中的点击

我正在审查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 

谢谢!

.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块的Hash beeing

您的代码的长版本将是:

 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 

TapObject类中的Ruby方法。

此方法将x生成块,然后返回x。 此方法用于“挖掘”方法链,以对链内的中间结果执行操作。