首页 > 解决方案 > Ruby 中的 3 点方法参数是什么?

问题描述

谁能解释一下这个语法:

def hello(...)
  p(...).to_a
end

hello 1,2,3,4 # => [1,2,3,4]

什么是类型...

标签: ruby

解决方案


我认为这篇文章将帮助您更好地理解它。简而言之,这是一种新的“速记语法”,用于引导参数以使代码“更简单”,现在call(*args, **kws, &block)您可以编写call(...)

这是一个简单的例子:

def perform(*args, **kws, &block)
  block.call(args, kws)
end

def call(...)
  perform(...)
end

> call(1, 2, 3, k1: 4, k2: 5) {|*x| puts x}
1
2
3
{:k1=>4, :k2=>5}

推荐阅读