开发者

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

开发者 https://www.devze.com 2023-02-15 12:29 出处:网络
When declaring a method, what do the various prefixes for t开发者_Go百科he arguments mean? sh(*cmd, &block)

When declaring a method, what do the various prefixes for t开发者_Go百科he arguments mean?

sh(*cmd, &block)

What does the * before cmd mean?

What does the & before block mean?


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

精彩评论

暂无评论...
验证码 换一张
取 消