声明方法时,各种参数前缀是什么意思? [英] When declaring a method, what do the various argument prefixes mean?

查看:55
本文介绍了声明方法时,各种参数前缀是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在声明一个方法时,参数的各种前缀是什么意思?

sh(*cmd, &block)

cmd前的*是什么意思?

block 之前的 & 是什么意思?

解决方案

星号 * 表示将所有剩余的参数组合成一个由该参数命名的列表.&符号 & 表示如果给方法调用一个块(即 block_given? 为真)然后将它存储在由参数命名的新 Proc 中(或参数,我猜).

def foo(*a)把 a.inspect结尾foo(:ok) # =>[:好的]foo(1, 2, 3) # =>[1, 2, 3]定义栏(&b)把 b. 检查结尾bar() # =>零酒吧(){|x|x+1} # =>#<Proc:0x0000000100352748>

请注意,& 必须出现在最后(如果使用),并且 * 可以在其之前倒数第二,或者必须在最后.>

* 运算符还可用于在调用时将数组扩展"为参数列表(而不是在定义中组合"它们),如下所示:

def gah(a, b, c)puts "OK: a=#{a}, b=#{b}, c=#{c}"结尾gah(*[1, 2, 3]) # =>好的:a=1,b=2,c=3"gah(1, *[2, 3]) # =>"OK: a=1, b=2, c=3" # 必须是最后一个参数.

类似地,& 运算符可用于在调用函数时将 Proc 对象扩展"为给定块:

def zapyield [1, 2, 3] 如果 block_given?结尾zap() # =>零zap(&Proc.new{|x|puts x.inspect}) # =>[1, 2, 3]

When declaring a method, what do the various prefixes for the 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]

这篇关于声明方法时,各种参数前缀是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆