In Ruby, what are the vertical lines?

后端 未结 4 2070
我寻月下人不归
我寻月下人不归 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
    
    0 讨论(0)
  • 2020-12-21 00:19

    It's for the parameters that are being passed to your block. i.e. in your example, upto will call your block with each number from 1 to 9 and the current value is available as x.

    The block parameters can have any name, just like method parameters. e.g. 1.upto(9) { |num| puts num } is valid.

    Just like parameters to a method you can also have multiple parameters to a block. e.g.

    hash.each_pair { |key, value| puts "#{key} is #{value}" }
    
    0 讨论(0)
  • 2020-12-21 00:20

    It's not an operator; it's delimiting the argument list for the block. The bars are equivalent to the parens in def foo(x). You can't write it as {print x |x} for the same reason this:

    def foo(x)
      puts "It's #{x}"
    end
    

    can't be rewritten as this:

    def foo
      puts "It's #{x}" (x
    end
    
    0 讨论(0)
  • 2020-12-21 00:22

    The vertical lines are use to denote parameters to the block. The block is the code enclosed within { }. This is really the syntax of the ruby block, parameters to the block and then the code.

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