When declaring a method, what do the various argument prefixes mean?

前端 未结 1 972
庸人自扰
庸人自扰 2021-01-06 19:37

When declaring a method, what do the various prefixes for the arguments mean?

sh(*cmd, &block)

What does the * before

相关标签:
1条回答
  • 2021-01-06 20:15

    The asterisk * means to combine all of the remaining arguments into a single list named by the argument. The ampersand & means that if a block is given to the method call (i.e. block_given? would be true) then store it in a new Proc named by the argument (or pseudo-argument, I guess).

    def foo(*a)
      puts a.inspect
    end
    foo(:ok) # => [:ok]
    foo(1, 2, 3) # => [1, 2, 3]
    
    def bar(&b)
      puts b.inspect
    end
    bar() # => nil
    bar() {|x| x+1} # => #<Proc:0x0000000100352748>
    

    Note that the & must appear last, if used, and the * could be next-to-last before it, or it must be last.

    The * operator can also be used to "expand" arrays into argument lists at call time (as opposed to "combining" them in a definition), like so:

    def gah(a, b, c)
      puts "OK: a=#{a}, b=#{b}, c=#{c}"
    end
    gah(*[1, 2, 3]) # => "OK: a=1, b=2, c=3"
    gah(1, *[2, 3]) # => "OK: a=1, b=2, c=3" # must be last arg.
    

    Similarly, the & operator can be used to "expand" a Proc object as the given block when calling a function:

    def zap
      yield [1, 2, 3] if block_given?
    end
    zap() # => nil
    zap(&Proc.new{|x|puts x.inspect}) # => [1, 2, 3]
    
    0 讨论(0)
提交回复
热议问题