Ruby 中的 *(星号)是什么意思? [英] What does the * (star) mean in Ruby?

查看:91
本文介绍了Ruby 中的 *(星号)是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
Ruby 中的 * 运算符对这个字符串做了什么

可能在别处有答案,但我只是不知道如何找到它...

Probably there is answer for that elsewhere, but I just don't know how to find it...

如果我是对的,如果在函数定义中使用 * 表示多个参数:

If I am right, the * means multiple parameters if used in function definition:

def hero(name, *super_powers)

但是*在这样的代码中做了什么:

But what does * do in the code like this:

Hash[*[[:first_name, 'Shane'], [:last_name, 'Harvie']].flatten] # => {:first_name=>"Shane", :last_name=>"Harvie"}

推荐答案

可变长度参数列表,星号运算符

Variable Length Argument List, Asterisk Operator

方法的最后一个参数前面可能有一个星号(*),它有时被称为splat"运算符.这表明可以将更多参数传递给函数.收集这些参数并创建一个数组.

The last parameter of a method may be preceded by an asterisk(*), which is sometimes called the 'splat' operator. This indicates that more parameters may be passed to the function. Those parameters are collected up and an array is created.

星号运算符也可以位于方法调用中的数组参数之前.在这种情况下,数组将被扩展,传入的值就像用逗号分隔一样.

The asterisk operator may also precede an Array argument in a method call. In this case the Array will be expanded and the values passed in as if they were separated by commas.

这篇关于Ruby 中的 *(星号)是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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