像tap这样的组合方法,但能够返回不同的值? [英] Combinatory method like tap, but able to return a different value?

查看:36
本文介绍了像tap这样的组合方法,但能够返回不同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在经历一个尝试避免临时变量和过度使用条件的阶段,我可以使用更流畅的编码风格.我非常喜欢在我想要获取需要返回的值的地方使用 #tap,但在返回之前先用它做一些事情.

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 using #tap in places where I want to get the value I need to return, but do something with it before I return it.

def fluid_method
  something_complicated(a, b, c).tap do |obj|
    obj.update(:x => y)
  end
end

对比.程序:

def non_fluid_method
  obj = something_complicated(a, b, c)
  obj.update(:x => y)
  obj # <= I don't like this, if it's avoidable
end

显然上面的例子很简单,但这是 ruby​​ 社区中非常常见的编码风格.我有时也会使用 #inject 来通过一系列过滤器传递一个对象:

Obviously the above examples are simple, but this is a pretty common coding style in the ruby community nonetheless. I'll sometimes use #inject to pass an object through a series of filters too:

things.inject(whatever) do |obj, thing|
  thing.filter(obj)
end

对比.程序:

obj = whatever
things.each do |thing|
  obj = thing.filter(obj)
end
obj

现在我面临着重复使用类似以下情况的问题,并正在寻找一种更流畅的方法来处理它:

Now I'm facing repeated use of a condition like the following, and looking for a more fluid approach to handling it:

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

(稍微)更干净的解决方案是以重复为代价避免临时变量:

The (slightly) cleaner solution is to avoid the temporary variable at the cost of duplication:

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

我不禁想在这里使用几乎的东西,比如#tap.

I can't help but feeling the desire to use something almost like #tap here though.

在这里我还可以遵循哪些其他模式.我意识到这对某些人来说只是无稽之谈,我应该转向更有趣的问题,但我正在努力学习以更实用的风格写作,所以我只是好奇长期的 ruby​​ists 已经确定了什么成为处理此类情况的好方法.这些示例得到了极大的简化.

What other patterns might I follow here. I realise this is all just nonsensical sugar to some people and that I should just move onto more interesting problems, but I'm trying to learn to write in a more functional style, so I'm just curious what long-term rubyists have determined to be good ways to tackle situations like this. These examples are hugely simplified.

推荐答案

Define Object#as:

class Object
  def as
    yield self
  end
end

现在你可以写:

def not_sure_this_is_nice_enough_method1
  something_complex(a, b, c).as do |obj| 
    a_predicate_check? ? obj.one_more_method_call : obj
  end
end

这篇关于像tap这样的组合方法,但能够返回不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆