了解Ruby中的点击

Man*_*eet 6 ruby ruby-on-rails

我正在审查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
Run Code Online (Sandbox Code Playgroud)

谢谢!

MrY*_*iji 13

.tap 在这里"对一系列方法中的中间结果进行操作"(引用ruby-doc).

换句话说,object.tap允许您object在块之后操作并返回它:

{}.tap{ |hash| hash[:video] = 'Batmaaaaan' }
# => return the hash itself with the key/value video equal to 'Batmaaaaan'
Run Code Online (Sandbox Code Playgroud)

所以你可以做这样的事情.tap:

{}.tap{ |h| h[:video] = 'Batmaaan' }[:video]
# => returns "Batmaaan"
Run Code Online (Sandbox Code Playgroud)

这相当于:

h = {}
h[:video] = 'Batmaaan'
return h[:video]
Run Code Online (Sandbox Code Playgroud)

一个更好的例子:

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`
Run Code Online (Sandbox Code Playgroud)

你的代码:

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
Run Code Online (Sandbox Code Playgroud)

正在返回一个填充在.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
Run Code Online (Sandbox Code Playgroud)