红宝石:"p * 1..10"中的星号是什么意思是

编程入门 行业动态 更新时间:2024-10-24 06:26:12
本文介绍了红宝石:"p * 1..10"中的星号是什么意思是的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

线

p *1..10

与...完全相同

(1..10).each { |x| puts x }

为您提供以下输出:

$ ruby -e "p *1..10" 1 2 3 4 5 6 7 8 9 10

例如,当与textmate一起使用时,这是一个很好的捷径,但是星号有什么作用?这是如何运作的?在网上找不到任何东西...

it's a great shortcut when working with textmate for example, but what does the asterisk do? how does that work? couldn't find anything on the net...

推荐答案

它是 splat运算符.您会经常看到它用于将数组拆分为函数的参数.

It's the splat operator. You'll often see it used to split an array into parameters to a function.

def my_function(param1, param2, param3) param1 + param2 + param3 end my_values = [2, 3, 5] my_function(*my_values) # returns 10

更常见的是,它用于接受任意数量的参数

More commonly it is used to accept an arbitrary number of arguments

def my_other_function(to_add, *other_args) other_args.map { |arg| arg + to_add } end my_other_function(1, 6, 7, 8) # returns [7, 8, 9]

它也适用于多个分配(尽管这两个语句在没有splat的情况下都可以使用):

It also works for multiple assignment (although both of these statements will work without the splat):

first, second, third = *my_values *my_new_array = 7, 11, 13

在您的示例中,这两个是等效的:

For your example, these two would be equivalent:

p *1..10 p 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

更多推荐

红宝石:"p * 1..10"中的星号是什么意思是

本文发布于:2023-08-01 04:23:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1265181.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:星号   红宝石   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!