ruby中tap方法的优点 [英] advantage of tap method in ruby

查看:43
本文介绍了ruby中tap方法的优点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚阅读了一篇博客文章,并注意到作者在如下片段中使用了 tap:

I was just reading a blog article and noticed that the author used tap in a snippet something like:

user = User.new.tap do |u|
  u.username = "foobar"
  u.save!
end

我的问题是使用 tap 到底有什么好处或优势?我不能做:

My question is what exactly is the benefit or advantage of using tap? Couldn't I just do:

user = User.new
user.username = "foobar"
user.save!

或者更好:

user = User.create! username: "foobar"

推荐答案

当读者遇到:

user = User.new
user.username = "foobar"
user.save!

他们必须遵循所有三行,然后才能认识到它只是在创建一个名为 user 的实例.

they would have to follow all the three lines and then recognize that it is just creating an instance named user.

如果是:

user = User.new.tap do |u|
  u.username = "foobar"
  u.save!
end

那么马上就清楚了.阅读器不必阅读块内的内容即可知道实例 user 已创建.

then that would be immediately clear. A reader would not have to read what is inside the block to know that an instance user is created.

这篇关于ruby中tap方法的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆