Ruby – What does various parameter prefixes mean when declaring methods?

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

sh(*cmd, &block)

What does the * before cmd mean?

What & what does it mean before the block

The asterisk * means that all The remaining parameters are combined into a single list named by the parameters. The ampersand & means that if a block is called to the method (i.e. block_given? will be true), it will be stored in a new Proc named by the parameter (or I guess it is Pseudo-parameter).

def foo(*a)
puts a.inspect
end
foo(:ok) # => [:ok]
foo(1, 2, 3) # => [1, 2, 3]

def bar(&b)
puts b.inspect< br />end
bar() # => nil
bar() {|x| x+1} # => #

Attention & must appear At the end, if used, and * may be the penultimate before it, or it must be the last.

The * operator can also be used to “expand” an array into a parameter list ( Instead of “combining” them in the definition), as follows:

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” the Proc object into a 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]< /pre>

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

sh(*cmd, &block)

What does the * before cmd mean?

What & what does it mean before the block

The asterisk * means to combine all the remaining parameters into a single list named by the parameters The & symbol & means that if a block is called to the method (i.e. block_given? will be true), it will be stored in a new Proc named by the parameter (or a dummy parameter, I guess).

< p>

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} # => #

Note & must appear at the end, if used, and * may precede it Is the penultimate, or it must be the last.

The * operator can also be used to "expand" an array into a parameter list (instead of "combining" them in the definition) when called, as follows Shown:

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 when calling a function "Expand" the Proc object into a given block:

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

Leave a Comment

Your email address will not be published.