红宝石:"p * 1..10"中的星号是什么意思是 [英] ruby: what does the asterisk in "p *1..10" mean

查看:146
本文介绍了红宝石:"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...

推荐答案

它是

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"中的星号是什么意思是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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