DAY 20
0

## Ruby Splat(*)符號使用

*符號英文稱為Asterisk或Splat，中文尚未看到統一稱呼，一般是稱為乘號或星號。一般常見於乘法，但在乘法用途中，是當做雙元運算子。當用作單元運算子的時候，他會有非常豐富多元的用途。

## 多個變數轉換為數列

*用於單元運算子，第一種用法是將一串變數轉換為數列：

``````*a = 1,2,3
# a = [1,2,3]
``````

``````def sum(*args)
puts args.inject(:+)
end

sum(1,2,3)
# => 6
``````

``````def say(person, *words)
words.each { |w| puts person + ": " + w }
end

say("John", "Hello", "My name is john", "I am 30 years old")
# => John: Hello
# => John: My name is john
# => John: I am 30 years old
``````

``````def say(*words, person)
words.each { |w| puts person + ": " + w }
end

say("Hello", "My name is john", "I am 30 years old", "John")
# => John: Hello
# => John: My name is john
# => John: I am 30 years old
``````

``````sentences = ["Hello", "Nice to meet you", "How are you?"]

say("Nancy", *sentences)
# => Nancy: Hello
# => Nancy: Nice to meet you
# => Nancy: How are you?
``````

## 多重指定變數Parallel Assignment

``````a,b = "hello ", "world"

puts a + b
# => hello world
``````

``````first, *all = [1,2,3,4,5]
# first = 1
# all = [2,3,4,5]

*all, last = [1,2,3,4,5]
# all = 1,2,3,4
# last = 5

first, *all, last = [1,2,3,4,5]
# first = 1
# all = [2,3,4]
# last = 5
``````

## 其他用法

``````def plus(a, b, *)
puts a + b
end

plus(1, 2, 3, 4, 5)
# => 3
``````