Search code examples
rubysymbolsimplicit-conversionproc

How to use a string instead of a symbol for `Symbol#to_proc` shorthand


a = (1..10).to_a
a.map(&:even?)
=> [false, true, false, true, false, true, false, true, false, true]

How to call map using a string that holds the method name?

foo = 'even?'
a.map(...foo...)

Solution

  • The shorthand syntax is not ampersand-colon, it is ampersand followed by a symbol:

    (1..10).map(& :even?)
    

    In Ruby methods are usually referred by symbols, so if you have a symbol in your variable this syntax works as expected:

    name = :even?
    (1..10).map(&name)
    

    If you don't have control over the variable method name, e.g. it is an argument, I would recommend using general method send instead. It works with both symbols & strings.

    def perform enum, name
      enum.each{ |e| e.send(name) }
    end
    
    perform 1..10, "even?"