How to dynamically create arguments for a method?

Being a little 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 to the end

Obviously, I can call it whatever I like, for example:

mytest ("one", "two", "three")

No problems. But I need to do this with a dynamically created set of arguments. For example, I pull the result set from the database, and I do not know how many records will return. Let's say I want to collect the result identifiers and call mytest () with them - how would I build a set of arguments to go to mytest ()?

It seems somehow obvious, but for some reason it is not. I understand that I can write mytest () instead to take an array or Hash, but I'm actually trying to call a method in a plugin that I did not write.

+3
source share
1 answer

I'm not sure I understood your question. You ask how to turn an array into method arguments? Read it

Let's say you have this:

a = [1,2,3,4]

and a method containing 4 parameters, for example:

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

You can call a method, for example:

whatever(*a)

and the elements of the array will be sent as you want.

+13
source

Source: https://habr.com/ru/post/1732073/


All Articles