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

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

sh(*cmd, &block)

What does it mean *to cmd?

What does it mean &to block?

+3
source share
1 answer

An asterisk *means combining all other arguments into one list, called an argument. Ampersand &means that if the block is passed to the method call (i.e. it block_given?will be true), then save it in a new Proc called an argument (or, as it seems to me, a pseudo-argument).

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 it &should be displayed last if used, and *may be the last before it, or it should be the last.

* "" ( "" ), :

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.

, & "" Proc :

def zap
  yield [1, 2, 3] if block_given?
end
zap() # => nil
zap(&Proc.new{|x|puts x.inspect}) # => [1, 2, 3]
+7

All Articles