链接 &符号上的 to_proc [英] Chaining & to_proc on symbol

查看:51
本文介绍了链接 &符号上的 to_proc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rubyist 众所周知 & 会在符号上调用 to_proc,所以

It's well known to Rubyist & will call to_proc on a symbol, so

[:a, :b, :c].map(&:to_s)

相当于

[:a, :b, :c].map { |e| e.to_s } # => ["a", "b", "c"]

假设我想在 to_s 之后立即调用另一个方法,这两个实现将起作用:

Say I want to call another method right after to_s, these two implementations will work:

[:a, :b, :c].map { |e| e.to_s.upcase }
[:a, :b, :c].map(&:to_s).map(&:upcase)

我的问题是,有没有办法将 & Symbol#to_proc 调用链接到一个参数中?类似的东西:

My question is, is there a way to chain the & Symbol#to_proc call in one parameter? Something like:

[:a, :b, :c].map(&:to_s:upcase)

谢谢!

推荐答案

如果你只是在做:

%i[a b c].map { |e| e.to_s.upcase }

然后只是使用块并继续处理更重要的事情.如果您确实在执行一系列 Enumerable 调用并发现这些块在视觉上过于嘈杂:

then just use the block and get on with more important things. If you're really doing a chain of Enumerable calls and find the blocks too visually noisy:

%i[a b c].map { |e| e.to_s.upcase }.some_chain_of_enumerable_calls...

然后你可以把你的逻辑扔进一个 lambda 来帮助清理外观:

then you could toss your logic into a lambda to help clean up the appearance:

to_s_upcase = lambda { |e| e.to_s.upcase }
%i[a b c].map(&to_s_upcase).some_chain_of_enumerable_calls...

或者把它扔到一个方法中然后说:

or throw it in a method and say:

%i[a b c].map(&method(:to_s_upcase)).some_chain_of_enumerable_calls...

无论哪种方式,您都在为您的一点点逻辑命名(这几乎是 &:symbol 为您所做的一切)以使代码更具可读性和更易于理解.在 to_s.upcase 的特定情况下,这有点毫无意义,但是当块变大时,这些方法非常有用.

Either way, you're giving your little bit of logic a name (which is pretty much all &:symbol is doing for you) to make the code more readable and easier to understand. In the specific case of to_s.upcase, this is all a bit pointless but these approaches are quite useful when the block gets bigger.

这篇关于链接 &符号上的 to_proc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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