使用Object#tap使代码更优雅
2015-06-14 14:01
204 查看
今天看spree源码的时候经常看到
先看下官方文档上tap的例子
Yields self to the block, and then returns self. The primary purpose of this method is to “tap into” a method chain, in order to perform operations on intermediate results within the chain.
tap在block里访问自身,然后迭代结束后返回自身,这样很容易插入方法链中。有点像是先打开caller,然后对caller进行操作,最后返回caller。
举个例子比较一下使用tap会对代码带来什么好处
可以看到,
Object#tap方法。以前只知道有这个方法,而且感觉这个方法调试的作用大于实际,今日看来以前的理解应该不够准确。
先看下官方文档上tap的例子
Yields self to the block, and then returns self. The primary purpose of this method is to “tap into” a method chain, in order to perform operations on intermediate results within the chain.
(1..10) .tap {|x| puts "original: #{x.inspect}"} .to_a .tap {|x| puts "array: #{x.inspect}"} .select {|x| x%2==0} .tap {|x| puts "evens: #{x.inspect}"} .map {|x| x*x} .tap {|x| puts "squares: #{x.inspect}"}
tap在block里访问自身,然后迭代结束后返回自身,这样很容易插入方法链中。有点像是先打开caller,然后对caller进行操作,最后返回caller。
举个例子比较一下使用tap会对代码带来什么好处
require 'ostruct' require 'pp' eason = OpenStruct.new eason.name = 'eason' eason.age = 30 eason.sex = 'male' def duplicate(obj) new_obj = obj.dup new_obj.name = 'new name' new_obj.age = 18 new_obj end def duplicate_with_tap(obj) obj.dup.tap do |new_obj| new_obj.name = 'new name' new_obj.age = 18 end end pp duplicate(eason) pp duplicate_with_tap(eason)
可以看到,
duplicate方法的最后一行需要显示的返回
new_obj,而
duplicate_with_tap方法中,
tap会自动返回自身,这样整个方法显得浑然一体,更加优雅。
相关文章推荐
- 学习笔记(objective-c)-重写description方法
- WebSocket使用javax.websocket.RemoteEndpoint.Basic.sendObject(Object arg0)向页面方法发送对象
- java笔记10 多态 Object类
- UGUI - 判断是否点击在UI 上 Bug,IsPointerOverGameObject()在移动端检测失败
- ObjectOutStream的reset方法
- 学习笔记(objective-c)-判断指针变量的实际类型
- Python标准库:内置函数vars([object])
- Python标准库:内置函数vars([object])
- 学习笔记(objective-c)-多态
- 【ObjectC】oc中的内存分配
- error: while loading shared libraries : countlib.so : cannnot open shared object file : No such fil
- Faq_flask : AttributeError: ‘module’ object has no attribute ‘autoescape’
- Objective-C语法之扩展(Extension)的使用
- Objective-C语法之字符串NSString去掉前后空格或回车符(可以是NSCharacterSet类型的其它字符)
- Objective-C语法之可变参数
- Objective-C语法之NSDictionary和NSMutableDictionary
- Objective-C语法之指针型参数
- Objective-C语法之nonatomic和atomic之间的区别
- Objective-C语法之NSSortDescriptor
- Objective-C语法之NSPredicate的使用