Ruby 我要搞懂你 (2) Splat operater

Fred Hung
Fred Hung
Sep 7, 2018 · 2 min read

定義非必要參數

splat operater (*) 用法通常在 method 的非必要參數上面

def add(*nums)
puts nums.inject(&:+)
end
add 1,2
# 3
add 1,2,3,4,5
# 10

延伸閱讀:Ruby Enumerable module 系列文-reduce(inject)

當然也可以給預設參數

def say(a=1,b=2)
puts a
puts b
end
say
#1
#2

double splat (**) 代表的是 hash 參數

def double_splat(**hash)
p hash
end

double_splat()
# => {}

double_s(a: 1)
# => {:a => 1}

double_splat(a: 1, b: 2)
# => {:a => 1, :b => 2}

double_splat('not a hash')
# error

array 操作

splat operater 也可以用來解構 array,
比如說將 array 解構後傳入函式中

def add(a, b)
puts a+b
end
nums = [1,2]
add *nums
# 3

強制轉換型別

words  = *"hello world"
# => ["hello world"]

解構 array

data = [1, 2, 3, 4]

a, *b = data
puts "#{a}, #{b}"
# => 1, [2, 3, 4]
*a, b = data
puts "#{a}, #{b}"
# => [1, 2, 3], 4

a, *b, c = data
puts "#{a}, #{b}, #{c}"
# => 1, [2, 3], 4

個人網誌版:https://www.spreered.com/knowing-ruby-splat-operater/

Fred Hung

Written by

Fred Hung

立志要做個好笑的軟體工程師

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade