What are those pipe symbols for in Ruby?

前端 未结 7 701
一个人的身影
一个人的身影 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:24
    @names.each do |name|
      puts "Hello #{name}!"
    end
    

    at http://www.ruby-lang.org/en/documentation/quickstart/4/ is accompanied by this explanation:

    each is a method that accepts a block of code then runs that block of code for every element in a list, and the bit between do and end is just such a block. A block is like an anonymous function or lambda. The variable between pipe characters is the parameter for this block.

    What happens here is that for every entry in a list, name is bound to that list element, and then the expression puts "Hello #{name}!" is run with that name.

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