Can someone explain Ruby's use of pipe characters in a block?

前端 未结 3 582
余生分开走
余生分开走 2020-12-23 17:10

Can someone explain to me Ruby\'s use of pipe characters in a block? I understand that it contains a variable name that will be assigned the data as it iterates. But what is

3条回答
  •  情深已故
    2020-12-23 17:37

    Block arguments follow all the same conventions as method parameters (at least as of 1.9): you can define optional arguments, variable length arg lists, defaults, etc. Here's a pretty decent summary.

    Some things to be aware of: because blocks see variables in the scope they were defined it, if you pass in an argument with the same name as an existing variable, it will "shadow" it - your block will see the passed in value and the original variable will be unchanged.

    i = 10
    25.times { | i | puts i }
    puts i #=> prints '10'
    

    Will print '10' at the end. Because sometimes this is desirable behavior even if you are not passing in a value (ie you want to make sure you don't accidentally clobber a variable from surrounding scope) you can specify block-local variable names after a semicolon after the argument list:

    x = 'foo'
    25.times { | i ; x | puts i; x = 'bar' }
    puts x #=> prints 'foo'
    

    Here, 'x' is local to the block, even though no value is passed in.

提交回复
热议问题