# 新手问题 Hash [*[p1,p2].transpose.flatten] 中的*是什么用法？

yakczh · 2016年03月15日 · 最后由 aippp 回复于 2017年06月21日 · 2278 次阅读
``````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
``````

``````a, b = *[1,2]
p a # 1
p b  # 2
``````

transpose 和 flatten 什么意思？？？坐等

aippp 回复

``````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]]
``````
EvanYa 回复