如何动态创建方法的参数?

发布于 2024-08-21 10:46:28 字数 378 浏览 4 评论 0原文

由于对 Ruby 还有些陌生,我不知道如何做到这一点...假设我有一个采用可变数量参数的方法:

def mytest(*args) 将 args.to_json 显然

我可以用我喜欢的任何东西来称呼它,例如:

mytest('one', 'two', ' Three')

没问题。但我需要做的是使用一组动态创建的参数来调用它。例如,我正在从数据库中提取结果集,但我不知道会返回多少条目。假设我想收集结果 id,并用它们调用 mytest() ——我将如何构建传递给 mytest() 的参数集?

这似乎是显而易见的,但无论出于何种原因,事实并非如此。我意识到我可以编写 mytest() 来获取数组或哈希,但我实际上是在尝试调用我没有编写的插件中的方法。

Being still somewhat new to Ruby, I'm not sure how to do this... Let's say I have a method that takes a variable number of arguments:

def mytest(*args)
puts args.to_json
end

Obviously I can call it with whatever I like, such as:

mytest('one', 'two', 'three')

No problem. But what I need to do is call it with a dynamically-created set of arguments. For example, I'm pulling a result set from the database, and I don't know how many entries will come back. Let's say I want to collect the result ids, and call mytest() with them -- how would I construct the set of arguments to pass to mytest()?

This seems somehow obvious, but for whatever reason, it isn't. I realize that I could instead write mytest() to take an array or Hash, but I'm actually trying to call a method in a plugin that I didn't write.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ら栖息 2024-08-28 10:46:28

我不确定我是否理解你的问题。您是在问如何将数组转换为方法的参数吗?阅读本文

假设您有这个:

a = [1,2,3,4]

和一个带有 4 个参数的方法,例如:

def whatever(p1,p2,p3,p4)
  # do whatever you want with them here
end

您可以像这样调用该方法:

whatever(*a)

并且数组的元素将按照您希望的方式发送。

I'm not sure I understood your question. Are you asking how to turn an array into the arguments of a method? Read this

Let's say you have this:

a = [1,2,3,4]

and a method taking 4 parameters, like:

def whatever(p1,p2,p3,p4)
  # do whatever you want with them here
end

You can call the method, like this:

whatever(*a)

and the array's elements will be sent the way you want them to.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文