Other Ruby Map Shorthand Notation

后端 未结 1 1711
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 23:22

I am aware of the shorthand for map that looks like:

[1, 2, 3, 4].map(&:to_s)
> [\"1\", \"2\", \"3\", \"4\"]

I was told this is shor

相关标签:
1条回答
  • 2020-12-31 00:13

    Unfortunately this shorthand notation (which calls "Symbol#to_proc") does not have a way to pass arguments to the method or block being called, so you couldn't even do the following:

    array_of_strings.map(&:include, 'l') #=> this would fail
    

    BUT, you are in luck because you don't actually need this shortcut to do what you are trying to do. The ampersand can convert a Proc or Lambda into a block, and vice-versa:

    my_routine = Proc.new { |str| str.upcase }
    %w{ one two three }.map &my_routine #=> ['ONE', 'TWO', 'THREE']
    

    Note the lack of the colon before my_routine. This is because we don't want to convert the :my_routine symbol into a proc by finding the method and calling .method on it, rather we want to convert the my_routine Proc into a block and pass it to map.

    Knowing this, you can even map a native Ruby method:

    %w{ one two three }.map &method(:p)
    

    The method method would take the p method and convert it into a Proc, and the & converts it into a block that gets passed to map. As a result, each item gets printed. This is the equivalent of this:

    %w{ one two three }.map { |s| p s }
    
    0 讨论(0)
提交回复
热议问题