Ruby do/end vs braces

后端 未结 3 2015
再見小時候
再見小時候 2020-12-30 00:43

Why does this map expression produce different results depending on whether I use braces or do/end?

a = [1,2,3,4,5]


p a.map { |n|
    n*2
}  
#=> [2,4,6         


        
相关标签:
3条回答
  • 2020-12-30 01:24

    That has to do with the difference in associativity of the { character and the do keyword.

    In the first case, the block is interpreted as a block argument to the map function. The result of the map function is the argument to the p function.

    In the second case, the block is interpreted as a block argument to the p function, while the a.map is interpreted as the first argument to the p function. Since a.map evaluates to a, this prints the original array. The block is effectively ignored in this case.

    0 讨论(0)
  • 2020-12-30 01:34

    With the do/end syntax you are passing the block to p as a second argument, rather than to the map. You get the same result with:

    p a.map
    

    The block is ignored by p as it does not produce anything on inspect.

    0 讨论(0)
  • 2020-12-30 01:42

    That's because the second line is interpreted as:

    p(a.map) do ... end
    

    instead of:

    p(a.map do ... end)
    

    The grammar is ambiguous in this case and do doesn't seem to bind as strongly as {.

    0 讨论(0)
提交回复
热议问题