翻译 Procs and brackets

alex_marmot · 2015年06月05日 · 1603 次阅读

Procs and brackets

原文地址:http://thingsinabucket.com/2015/05/20/pocs_and_brackets/

Ruby 新手渣翻,如有错误,烦请赐教~

在 Hash 中做查找是一件简单,易读,有趣的事。


    dictionary['ruby']
    # => 'A precious stone'

在数组中做查找就不那么有趣了。

    term = 'ruby'
    (list_of_definitions.find { |definition| definition[:term] == term} || {})[:definition]
    # => 'A precious stone'

通过使用一点 proc 的小技巧,我们就能实现能查找任何类型的 Hash 查找符号。

    dictionary = ->(word) {
      (
        list_of_definitions.find{ |definition| definition[:item] == item } || {}
      )[:definition]
    }
    dictionary['ruby']

Ruby proc 支持用 `[]` 符号来进行调用。通过这个知识,我们可以用自己的语法糖来实现任何复杂的查找。
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请 注册新账号