- 论坛徽章:
- 0
|
本帖最后由 feiyang10086 于 2012-03-06 11:47 编辑
ruby block的用途和理解
lambdarubyrspec
在论坛讨论问题,自己写体会抄回来
常用到的场合:
1. scope 当需要动态参数时
Ruby代码- scope :aged_0, lambda{ where("created_at IS NULL OR created_at < ?", Date.today + 30.days).joins(:owner) }
- scope :aged_1, lambda{ |d_time|where("created_at IS NULL OR created_at < ?", d_time).joins(:owner) }
- scope :aged_0, lambda{ where("created_at IS NULL OR created_at < ?", Date.today + 30.days).joins(:owner) }
- scope :aged_1, lambda{ |d_time|where("created_at IS NULL OR created_at < ?", d_time).joins(:owner) }
复制代码 2. rspec测试
Ruby代码- lambda{post :create, :user => @attr}.should_not change(User, :count)
- lambda{post :create, :user => @attr}.should_not change(User, :count)
复制代码 参考文献,很多推荐
http://www.robertsosinski.com/20 ... -procs-and-lambdas/
block本质是匿名方法,和hash loop class recursion一样就是一个编程的工具,没有的话程序都可以写,就是特别的场合,有特别适用的地方。
那么,block匿名方法什么时候适用呢?方便理解也举个例子吧,
有两组数据,可能要进行不同处理
Ruby代码- def cross_loop(array_a, array_b, process)
- array_a.each do |element_a|
- array_b.each do |element_b|
- process.call(element_a, element_b)
- end
- end
- end
-
- cross_loop([1,2,3], [3,4,5], lambda{|x,y| puts x + y})
- cross_loop([1,2,3], [3,4,5], lambda{|x,y| puts x * y})
- def cross_loop(array_a, array_b, process)
- array_a.each do |element_a|
- array_b.each do |element_b|
- process.call(element_a, element_b)
- end
- end
- end
- cross_loop([1,2,3], [3,4,5], lambda{|x,y| puts x + y})
- cross_loop([1,2,3], [3,4,5], lambda{|x,y| puts x * y})
复制代码 说不用lambda行不行,当然,最基本可以在cross_loop里面调用一个函数。只不过重用的时候不好,因为没有process的参数。
当然,也可以不用lambda又动态传入process,写个process.call然后,再写些process函数也可以。
Ruby代码- def cross_loop(array_a, array_b, process)
- array_a.each do |element_a|
- array_b.each do |element_b|
- self.send(process, element_a, element_b)
- end
- end
- end
- def plus(a, b); puts a + b; end
- def multiply(a, b); puts a * b; end
- cross_loop([1,2,3], [3,4,5], 'plus')
- cross_loop([1,2,3], [3,4,5], 'multiply')
- def cross_loop(array_a, array_b, process)
- array_a.each do |element_a|
- array_b.each do |element_b|
- self.send(process, element_a, element_b)
- end
- end
- end
- def plus(a, b); puts a + b; end
- def multiply(a, b); puts a * b; end
- cross_loop([1,2,3], [3,4,5], 'plus')
- cross_loop([1,2,3], [3,4,5], 'multiply'
复制代码 )
|
|