Combinatory method like tap, but able to return a different value?

前端 未结 5 1727
时光取名叫无心
时光取名叫无心 2020-12-24 06:00

I\'m going through a phase of trying to avoid temporary variables and over-use of conditional where I can use a more fluid style of coding. I\'ve taken a great liking to us

5条回答
  •  渐次进展
    2020-12-24 07:04

    I found a method in the Facets gem that might be what you were looking for: Kernel#ergo

    So your original method:

    def not_nice_method
      obj = something_complex(a, b, c)
      if a_predicate_check?
        obj.one_more_method_call
      else
        obj
      end
    end
    

    might end up looking something like this:

    require 'facets/kernel/ergo'
    
    def nice_method
      something_complex(a, b, c).ergo do |_| 
        a_predicate_check? ? _.one_more_method_call : _
      end
    end
    

提交回复
热议问题