美文网首页Ruby & Rails
*args( splat 操作符)

*args( splat 操作符)

作者: 云莉6 | 来源:发表于2017-10-27 19:38 被阅读3次

注:*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

相关文章

  • *args( splat 操作符)

    注:*args, * 后面是自定义的变量名。如 *names。 这是一个 splat 操作符,它是 ruby 的方...

  • TS 函数新特性

    # 1:rest and spread操作符 --- ...args No 1 : 用来声明任意数量的方法参数 f...

  • Double Splat operator

    分享两篇文章,介绍Splat operator和Ruby2.0引入的Double Splat operator. ...

  • unity地形Splat替换

    1.将地形的splat导出 因为我实际话的地形是2048注意导出的时候要输入2047 可以看到splat贴图被导出...

  • 「回归」——Splat!

    嗒哒!我又出场啦!好久不见,今天我要给大家介绍一套书—— Splat ! 《斯普拉特在...

  • 02-06 AOP学习之@args,@annotation,be

    Spring AOP @args,@annotation和bean使用示例 @args:使用“@args(注解列表...

  • args...、##args、#、##、__VA_ARGS__和

    直接看结果: 说明:...和__VA_ARGS__:括号内 ... 的内容原样抄写在VA_ARGS_ 的位置。ar...

  • 2020-06-16 Splat 模型模拟参数详解

    Splat simulation parameters clp 16 June, 2020 本教程更详细地描述了S...

  • ``` def a(*args): for i in args: print i ```

  • *args

    一、*args的使用方法 二、**kwargs的使用方法 三个特性 lambda函数有如下特性: lambda函数...

网友评论

    本文标题:*args( splat 操作符)

    本文链接:https://www.haomeiwen.com/subject/cmudpxtx.html