*args( splat 操作符)

注:*args, * 后面是自定义的变量名。如 *names

这是一个 splat 操作符,它是 ruby 的方法,不是 rails 特有的,根据不同应用场景,它有两种应用方式:

  • 将多个参数打包成一个数组
  • 将数组拆分成一个参数列表
  1. 如果在方法定义中使用 splat 操作符,那么这个方法就可以接受任意数量的参数,参数列表会被打包到一个数组中。
def foo(*args)
  args.each_with_index{ |arg, i| puts "#{i+1}. #{arg}" }
end

# 将参数列表打包成数组
foo("a", "b", "c")
# 1. a   <== this is the output
# 2. b
# 3. c

foo1(1, 2, 3, 4, 5)

# 把前面的参数打包成数组
def foo1(*other_args, arg1, arg2)
  p arg1.inspect       # => 4
  p arg2.inspect       # => 5
  p other_args.inspect # => [1, 2, 3]
end

# 把剩余的参数打包成数组
def foo1(arg1, arg2, *other_args)
  p arg1.inspect       # => 1
  p arg2.inspect       # => 2
  p other_args.inspect # => [3, 4, 5]
end

# 把中间的参数打包成数组
def foo1(arg1, *other_args, arg2)
  p arg1.inspect       # => 1
  p arg2.inspect       # => 5
  p other_args.inspect # => [2, 3, 4]
end
  1. 如果在调用方法的时候,在数组前面加上 *,方法体内,会把数组拆分成参数进行运算和处理。
def bar(a, b, c)
  a + b + c
end

# 将数组拆分成参数列表
my_array = [1, 2, 3]
bar(*my_array)
# 6

# 将数组拆分成参数列表
foo(*my_array)
# 1. 1   <== this is the output
# 2. 2
# 3. 3
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容