Search code examples
rubysymbolsproc

Chaining & to_proc on symbol


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

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

is equivalent to

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

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)

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)

Thanks!


Solution

  • If you're only doing:

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

    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...
    

    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...
    

    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.