In Ruby, what are the vertical lines?

后端 未结 4 2081
我寻月下人不归
我寻月下人不归 2020-12-20 23:23
1.upto(9) { |x| print x }

Why won\'t this work?

{ print x |x} }

What about y?

4条回答
  •  旧巷少年郎
    2020-12-21 00:06

    In the piece of code you have specified, vertical lines are a part of the block definition syntax. So { |x| print x } is a block of code provided as a parameter to the upto method, 9 is also a parameter passed to the upto method.

    Block of code is represented by a lambda or an object of class Proc in Ruby. lambda in this case is an anonymous function.

    So just to draw an analogy to the function definition syntax,

    def function_name(foo, bar, baz)
      # Do something
    end
    
    
    {       # def function_name (Does not need a name, since its anonymous)
    |x|     #   (foo, bar, baz)
    print x #   # Do Something
    }       # end
    

提交回复
热议问题