Ruby 代码中的(一元)* 运算符有什么作用? [英] What does the (unary) * operator do in this Ruby code?

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

问题描述

给定 Ruby 代码

line = "first_name=mickey;last_name=mouse;country=usa"record = Hash[*line.split(/=|;/)]

除了 * 运算符之外,我理解第二行中的所有内容 - 它在做什么,它的文档在哪里?(正如您可能猜到的,事实证明,搜索此案例很困难...)

解决方案

*splat 运算符.

它将 Array 扩展为参数列表,在本例中为 Hash.[] 方法的参数列表.(更准确地说,它扩展了任何响应 to_ary/to_ato_a 在 Ruby 1.9 中的对象.)

为了说明,以下两个语句是相等的:

方法 arg1、arg2、arg3方法 *[arg1, arg2, arg3]

它还可以在不同的上下文中使用,以捕获方法定义中所有剩余的方法参数.在这种情况下,它不会扩展,而是合并:

def method2(*args) # args 将保存所有参数的数组结尾

这里有一些更详细的信息.>

Given the Ruby code

line = "first_name=mickey;last_name=mouse;country=usa" 
record = Hash[*line.split(/=|;/)] 

I understand everything in the second line apart from the * operator - what is it doing and where is the documentation for this? (as you might guess, searching for this case is proving hard...)

解决方案

The * is the splat operator.

It expands an Array into a list of arguments, in this case a list of arguments to the Hash.[] method. (To be more precise, it expands any object that responds to to_ary/to_a, or to_a in Ruby 1.9.)

To illustrate, the following two statements are equal:

method arg1, arg2, arg3
method *[arg1, arg2, arg3]

It can also be used in a different context, to catch all remaining method arguments in a method definition. In that case, it does not expand, but combine:

def method2(*args)  # args will hold Array of all arguments
end

Some more detailed information here.

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

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