What are those pipe symbols for in Ruby?

前端 未结 7 740
一个人的身影
一个人的身影 2020-11-30 01:57

What are the pipe symbols for in Ruby?

I\'m learning Ruby and RoR, coming from a PHP and Java background, but I keep coming across code like this:

de         


        
7条回答
  •  抹茶落季
    2020-11-30 02:15

    They are the variables yielded to the block.

    def this_method_takes_a_block
      yield(5)
    end
    
    this_method_takes_a_block do |num|
      puts num
    end
    

    Which outputs "5". A more arcane example:

    def this_silly_method_too(num)
      yield(num + 5)
    end
    
    this_silly_method_too(3) do |wtf|
      puts wtf + 1
    end
    

    The output is "9".

提交回复
热议问题