Chaining & to_proc on symbol

后端 未结 5 752
深忆病人
深忆病人 2020-12-09 22:26

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

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

is equivalent to

5条回答
  •  时光取名叫无心
    2020-12-09 23:00

    While we're playing with syntax, how about monkey-patching Array with a to_proc method?

    class Array
      def to_proc
        return :itself.to_proc if empty?
        ->(obj) { drop(1).to_proc.call(first.to_proc.call(obj)) }
      end
    end
    
    ["foo", "bar", "baz"].map(&[:capitalize, :swapcase, :chars, ->a{ a.join("-") }])
    # => ["f-O-O", "b-A-R", "b-A-Z"]
    

    See it on repl.it: https://repl.it/JS4B/1

提交回复
热议问题