Ruby 中使用的独立 splat 运算符 (*) 是什么? [英] What is the standalone splat operator (*) used for in Ruby?

查看:53
本文介绍了Ruby 中使用的独立 splat 运算符 (*) 是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚遇到了这个例子,其中在方法定义中单独使用了 splat 运算符:

I just came across this example where the splat operator is used by itself in a method definition:

def print_pair(a,b,*)
  puts "#{a} and #{b}"
end

print_pair(1,2,3,:cake,7)
#=> 1 and 2

很清楚你会在这样的上下文中使用它的内容和原因:

It is clear what and why you would use it in a context like so:

def arguments_and_opts(*args, opts)
  puts "arguments: #{args} options: #{opts}"
end

arguments_and_opts(1,2,3, a: 5)
#=> arguments: [1, 2, 3] options: {:a=>5}

但是为什么以及如何在第一个示例中使用它?既然它是在 Ruby 规范中定义的,那么它必须有一个用例吗?

But why and how would you use it in the first example? Since it is defined in the Ruby specs there must be a usecase for it?

推荐答案

在参数列表中,*args 的意思是将数组中剩余的所有参数都吞掉,并将它们绑定到名为 <代码>参数".* 表示吞噬所有剩余的参数并将它们绑定到任何内容",或者更简单地说忽略所有剩余的参数".

In a parameter list, *args means "gobble up all the remaining arguments in an array and bind them to the parameter named args". * means "gobble up all the remaining arguments and bind them to nothing", or put more simply "ignore all remaining arguments".

这正是你会使用它的时候:当你想忽略所有剩余的参数时.要么是因为你不关心他们,要么是因为不关心他们(但其他人可能):

And that's exactly when you would use this: when you want to ignore all the remaining arguments. Either because you don't care about them, or because you don't care about them (but someone else might):

def foo(*)
  # do something
  super
end

记住:没有参数列表的 super 将参数原封不动地传递.因此,即使 foothis 覆盖忽略了参数,它们仍然可用于超类的方法实现;然而,定义清楚地表明这个实现并不关心.

Remember: super without an argument list passes the arguments along unmodified. So, even though this override of foo ignored the arguments, they are still available to the superclass's implementations of the method; yet, the definition makes it clear that this implementation doesn't care.

这篇关于Ruby 中使用的独立 splat 运算符 (*) 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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