Search code examples
rubydictionaryblock

Is it possible to express `stuff.map {|x| puts x}` more succinctly?


I would like to use some sort of shorthand to express the following:

stuff.map {|x| puts x}

to something like this:

stuff.map {puts}

I cannot figure out the syntax. Can someone show me how to do this?


Solution

  • Since you have an array, you could just write

    puts stuff
    

    However, in general, you can add a method to String or Object that can then be passed directly to an Enumerable. Since Symbol has a to_proc method, you can have that method called without needing a block.

    class Object; def myputs; puts self; nil; end; end
    
    stuff.each &:myputs # or, even better, ...
    
    stuff.myputs