如何动态创建方法的参数?
由于对 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定我是否理解你的问题。您是在问如何将数组转换为方法的参数吗?阅读本文
假设您有这个:
和一个带有 4 个参数的方法,例如:
您可以像这样调用该方法:
并且数组的元素将按照您希望的方式发送。
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:
and a method taking 4 parameters, like:
You can call the method, like this:
and the array's elements will be sent the way you want them to.