注:*args
, *
后面是自定義的變量名。如 *names
。
這是一個(gè) splat
操作符固以,它是 ruby 的方法,不是 rails 特有的攒庵,根據(jù)不同應(yīng)用場景嘴纺,它有兩種應(yīng)用方式:
- 將多個(gè)參數(shù)打包成一個(gè)數(shù)組
- 將數(shù)組拆分成一個(gè)參數(shù)列表
- 如果在方法定義中使用
splat
操作符,那么這個(gè)方法就可以接受任意數(shù)量的參數(shù)浓冒,參數(shù)列表會被打包到一個(gè)數(shù)組中栽渴。
def foo(*args)
args.each_with_index{ |arg, i| puts "#{i+1}. #{arg}" }
end
# 將參數(shù)列表打包成數(shù)組
foo("a", "b", "c")
# 1. a <== this is the output
# 2. b
# 3. c
foo1(1, 2, 3, 4, 5)
# 把前面的參數(shù)打包成數(shù)組
def foo1(*other_args, arg1, arg2)
p arg1.inspect # => 4
p arg2.inspect # => 5
p other_args.inspect # => [1, 2, 3]
end
# 把剩余的參數(shù)打包成數(shù)組
def foo1(arg1, arg2, *other_args)
p arg1.inspect # => 1
p arg2.inspect # => 2
p other_args.inspect # => [3, 4, 5]
end
# 把中間的參數(shù)打包成數(shù)組
def foo1(arg1, *other_args, arg2)
p arg1.inspect # => 1
p arg2.inspect # => 5
p other_args.inspect # => [2, 3, 4]
end
- 如果在調(diào)用方法的時(shí)候,在數(shù)組前面加上
*
稳懒,方法體內(nèi)闲擦,會把數(shù)組拆分成參數(shù)進(jìn)行運(yùn)算和處理。
def bar(a, b, c)
a + b + c
end
# 將數(shù)組拆分成參數(shù)列表
my_array = [1, 2, 3]
bar(*my_array)
# 6
# 將數(shù)組拆分成參數(shù)列表
foo(*my_array)
# 1. 1 <== this is the output
# 2. 2
# 3. 3