`
vivimusing
  • 浏览: 78626 次
  • 性别: Icon_minigender_1
  • 来自: 台州
社区版块
存档分类
最新评论

Object#returning

阅读更多

      ActiveSupport 是Rails中的无名英雄。那些大量让Rails代码更加漂亮和强大的功能在ActiveSupport中实现。它加了很多在Rails中普遍使用的方法到核心类中。如果你不介意花时间发觉它们,你会学习到各种方便的技巧,且能应用到你的程序中。

先看下下面这个习惯用法

def create_book
  book = Book.new
  book.title = "Trafalgar: The Nelson Touch"
  book.author = "David Howarth"
  @db.add(book)
  book
end

     你创建了一个对象,给对象设置属性,然后返回这个对象。ActiveSupport 中加入了一个可以让习惯用法美化(在某些情况下,简化)的新的方法(叫 returning)到Object中。

def create_book
  returning Book.new do |book|
    book.title = "Trafalgar: The Nelson Touch"
    book.author = "David Howarth"
    @db.add(book)
  end
end

    后者是没有短于前者,但内容更优雅。我感觉更“ Rubyish ” 。有些时候,它可以为您节省几行代码,如果这很重要的。 (只需浏览下Rails代码就能找到更多的例子。 )

    Object#returing在Rails中已在相当长的一段时间,被检测是在2005年3月20号的第949修订 。 (它现在存在于active_support / core_ext /object/ misc.rb ,和原来的略有不同,不过还是很简短)

    找这个方法的注释你会发现“A Ruby-ized realization of the K combinator, courtesy of Mikael Brockman.”

。。。。。。

。。。。。。

。。。。。。

这个实现非常简明扼要:

 

def returning(value)
  yield(value)
  value
end

 

分享到:
评论
2 楼 vivimusing 2009-01-31  
对的就那篇文章。工作中看到returing,不解是什么东西,然后google到《Mining ActiveSupport: Object#returning?》 只翻译了一部分。你对于SKI组合子的解释让我长了见识了,谢谢
1 楼 RednaxelaFX 2009-01-31  
原文是这个么:Mining ActiveSupport: Object#returning?翻译的话可能最好还是给出原文链接比较好 ^ ^

话说这个“K Combinator”,也就是K组合子,算是函数式编程里比较重要的一个东西呢。所谓的SKI组合子能够组合出所有其它的组合子。
用Ruby语法来写,SKI组合子可以这样写:
def I(x)
  x
end

def K(x, &y)
  y[x]
  x
end

def S(x, y, z) # x and y have to be lambdas
  x[z][y[z]]
end

这样的K组合子就跟ActiveSupport里的一样。

Ruby 1.9里的Object#tap也是一个K组合子的实现,与Object#returning不同的是,前者是一个方法,K组合子的第一个参数就是caller,第二个参数是一个block;而后者其实是一个函数,K组合子的第一个参数是这个函数的第一个参数,隐式的第二个参数是一个block,只不过把函数定义在Object里让所有对象都能直接用。
Object.new.tap do |obj|
  def obj.foo
    # ...
  end
end

相关推荐

    findbugs常见Bug以及处理办法

    May expose internal representation by returning reference to mutable object 描述:调用get方法,获得对象属性,获得的对象属性是一个可变的对象; b) 建议处理 Dead store to local variable 描述:对一个局部...

    Programming in Objective-C 4th Edition

    Extension Through Inheritance: Adding New Methods 156 A Point Class and Object Allocation 160 The @class Directive 161 Classes Owning Their Objects 165 Overriding Methods 169 Which Method Is Selected?...

    Undocumented Windows 2000 Secrets 中文版

    这是一本涉及windows2000内核调试器、本地API(native API)、内核驱动、win2k对象管理(Windows 2000 Object Management)等方面的书籍,其价值性可以从UNDOCUMENTED 字眼中表现出来。 对于开发系统级程序、安全软件...

    IntraWeb v14.0.23 Ultimate for RAD Studio XE-XE5 (x32+x64)

    A Slim Reader/Writer lock object is used in TIWStandAloneServer and TIWServerInternalFiles instead of TMultiReadExclusiveWriteSynchronizer object. This new lock is available under Windows Vista and up...

    FlexGraphics_V_1.79_D4-XE10.2_Downloadly.ir

    When returning from ftmPanning mode the complete client area repainting will perform. - ADD: Added TFlexPanel.FrostPanFullDoc property. When true then in ftmPanning mode the whole document image ...

    stdafx.h代码

    // CDocTemplate manager object ///////////////////////////////////////////////////////////////////////////// // Type modifier for message handlers #ifndef afx_msg #define afx_msg // intentional ...

    Python中return self的用法详解

    在Python中,有些开源项目中...Returning self from a method simply means that your method returns a reference to the instance object on which it was called. This can sometimes be seen in use with object or

    msgpack-python-0.4.2.tar

    read an entire message from the stream, respectively deserialising and returning the result, or ignoring it. The latter two methods return the number of elements in the upcoming container, so that ...

    spring aop 实现源代码--xml and annotation(带lib包)

    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { 7. System.out.println("Log after " + method + " by LogAfterAdvice."); 8. } 9. } ...

    stream-converter:将任何内容转换为Node.js ReadStream

    流转换器 将任何内容转换为Node.js ReadStream,即 。 安装 npm install stream-converter...实际上,它不会进行任何转换,只是returning作为param传递的stream ,它将识别以及Node.js Core。 转换缓冲区或字符串 //o

    c++-today.pdf

    Now that software development is shifting primarily toward mobile and cloud computing, the venerable C++ programming language is returning to the dominant position it held during the object-oriented ...

    AutomaticCoder.zip

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSDictionary *json = [data objectFromJSONData]; //init object Person *person = [[Person alloc] ...

    lodash underscore js库速查手册

    Collection Functions (Arrays or Objects) _.each(list, iterator, [context]) Alias: forEach Iterates ... Useful for transmuting the arguments object. _.size(list) Return the number of values in the list.

    python正则表达式re之compile函数解析

    re正则表达式模块还包括一些有用的操作正则...Compile a regular expression pattern, returning a pattern object. 通过help可以看到compile方法的介绍,返回一个pattern对象,但是却没有对第二个参数flags进行介绍。

    service-runner:通用 nodejs 服务主管

    服务运行者通用 nodejs 服务运行器和主管特征以最小的接口以通用方式监督和... // Start the app, returning a promise. // Return an object with a `close()` function for clean shut-down support. // (ex: node

    Python正则表达式常用函数总结

     returning a match object, or None if no match was found. 函数作用: re.match函数尝试从字符串的开头开始匹配一个模式,如果匹配成功,返回一个匹配成功的对象,否则返回None。 参数说明: pattern:匹配的...

    ScalaMock:本机Scala模拟框架

    官方网站: 例子期望第一的风格test( " drawline interaction with turtle " ) { // Create mock Turtle object val m = mock[ Turtle ] // Set expectations (m.setPosition _).expects( 10.0 , 10.0 ) (m.forward...

    Effective C++(第三版)

    avoid returning “handles” to object internals. 条款29:为“异常安全”而努力是值得的 strive for exception-safe code. 条款30:透彻了解inlining的里里外外 understand the ins and outs of inlining. 条款31...

    笨方法学python3 Learn Python 3 the Hard Way

    笨方法学Python号称最经典的python入门书籍现在出python3版本的了,... Returning professionals who haven’t written code in years Seasoned professionals looking for a fast, simple, crash course in Python 3

    findbug 常见异常处理

    May expose internal representation by returning reference to mutable object 描述:调用get方法,获得对象属性,获得的对象属性是一个可变的对象; b) 建议处理 Dead store to local variable 描述:对一个局部...

Global site tag (gtag.js) - Google Analytics