【问题标题】:How can i make this code, more Ruby-esque?我怎样才能使这个代码,更像Ruby-esque?
【发布时间】:2010-05-07 14:31:47
【问题描述】:
unless scope.nil?
  @page ||= Page.find(id, :scope => Page.find(scope) )
else
  @page ||= Page.find(id)
end

【问题讨论】:

  • 以后,请将代码缩进四个空格,以便在 Stack Overflow 上显示时实际上看起来像 code

标签: ruby refactoring


【解决方案1】:
@page ||=  Page.find id, :scope => (Page.find scope if scope)

【讨论】:

  • 这当然是最整洁的,正如最后提到的,它当然取决于偏好。
【解决方案2】:

这有点干了:

find_opts = scope.nil? ? {} : {:scope => Page.find(scope)}
@page ||= Page.find(id, find_opts)

【讨论】:

    【解决方案3】:

    我会像下面这样写有问题的块。这真的归结为偏好,但我发现这种方式是最易读的。

    @page ||=
      if scope
        Page.find id, :scope => Page.find(scope)
      else
        Page.find id
      end
    

    【讨论】:

      【解决方案4】:

      你可以这样做:

      @page ||= unless scope.nil?
        Page.find(id, :scope => Page.find(scope))
      else
        Page.find(id)
      end
      

      【讨论】:

        【解决方案5】:

        或者:

        @page ||= scope.nil? ? Page.find(id) : Page.find(id, :scope => Page.find(scope))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-23
          相关资源
          最近更新 更多