p1 = ['bj', 'sh', 'sz'];
p2 = [100,200,300];
puts *[p1,p2].transpose.flatten
p=Hash[*[p1,p2].transpose.flatten]
puts p
不是很会描述,大概是将一个数组打散作为参数
def test(a, b)
puts a
puts "====="
puts b
end
my_arr = [1, 2]
test(*my_arr)
test(my_arr)
楼上正解,补充一点:
def test_asterisk_in_define(*args)
p args
end
test_asterisk_in_define 1, 2, 3 # => [1, 2, 3]
def test_asterisk_in_invoke(a, b, c)
p a
p b
p c
end
args = [1, 2, 3]
test_asterisk_in_invoke *args
# =>
# 1
# 2
# 3
More commonly it is used to accept an arbitrary number of arguments
def foo(*args)
args #it's an array.
end
It's the splat operator. You'll often see it used to split an array into parameters to a function.
## e.g. 1
def my_function(param1, param2, param3)
param1 + param2 + param3
end
my_values = [2, 3, 5]
my_function(*my_values) # returns 10
## e.g. 2
p *1..10
p 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
这个操作符的英文名叫 the splat operator,作用是对数组进行 unpack,或者对传入参数进行 pack,具体用法可以看下 ruby language spec/array spec。 个人倾向翻译成 打包/解包 ,译法参考自 Python 中类似语法。
官方例子
a = [[1,2], [3,4], [5,6]]
a.transpose #=> [[1, 3, 5], [2, 4, 6]]
s = [ 1, 2, 3 ] #=> [1, 2, 3]
t = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]]
a = [ s, t, 9, 10 ] #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
a.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = [ 1, 2, [3, [4, 5] ] ]
a.flatten(1) #=> [1, 2, 3, [4, 5]]