Ruby中使用的是什么?

时间:2014-08-21 13:01:32

标签: ruby

*之前做什么'测试'在下面的代码和Ruby编程语言中?

  def sample (*test)
       puts "The number of parameters is #{test.length}"
       for i in 0...test.length
          puts "The parameters are #{test[i]}"
       end
    end
    sample "Zara", "6", "F"
    sample "Mac", "36", "M", "MCA"

2 个答案:

答案 0 :(得分:7)

方法的最后一个参数前面可能是星号(*),有时也称为“splat”运算符。这表示可以将更多参数传递给函数。收集这些参数并创建一个数组。

示例:

def sample (*test)
    puts test
end

并将其命名为:

sample(1,2,3)

将返回数组:[1,2,3]

irb(main):001:0> def s(*t)
irb(main):002:1> puts t
irb(main):003:1> end
=> nil
irb(main):004:0> s(1,2,3)
1
2
3
=> nil

答案 1 :(得分:2)

OxAX提到了*前缀运算符的一个很好的用法 - to collect arguments,这就是它在你的例子中所做的。

def lots_of_args *args
  p args
end
lots_of_args 1,2,3 # => [1, 2, 3]

first, *rest = 1, 2, 3, 4
first # => 1
rest  # => [2, 3, 4]

我们甚至可以在方法定义之外应用它。


然而,重要的是要注意它还有另一个好处:

def add_three_nums a, b, c
  a + b + c
end

add_three_nums *[1,2,3]  # => 6
# same as calling "add_three_nums 1,2,3"

本质上,*运算符将一个数组的方法参数扩展为一个参数列表。


甚至还有第三个用例:

first, *rest = [1, 2, 3, 4]
first # => 1
rest  # => [2, 3, 4]

这第三种情况与第一种情况有些相似。但请注意,我们从数组中获取firstrest的值,而不是从值列表中获取值。


相关问题