Ruby do/end vs braces

后端 未结 3 2030
再見小時候
再見小時候 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: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 {.

提交回复
热议问题