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

查看:26
本文介绍了ruby:“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

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

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