venturemoo
venturemoo

Reputation: 3

Ruby Net::Http Api , Sending Multiple Parameters with GET/POST

I try to create a generic method to send GET/POST data with parameters using Ruby using NET:HTTP api ( https://apidock.com/ruby/Net/HTTP). Therefore, the number of parameters is not fixed. I know how to add a form data, as it is explained at : Get HTTP request in Ruby, I use;

uri = URI('http://www.example.com/todo.cgi') 
req = Net::HTTP::Post.new(uri.path)
req.set_form_data('from' => '2005-01-01', 'to' => '2005-03-31')

However it works when I know how many parameters I will have. I tried this but could not find how to add data instead of replacing.

parameter_list.each_with_index do |param,index|
req.set_form_data(param.to_s => value_list[index])
end

How can I make "For each parameter in my parameter list, add form data"?

Upvotes: 0

Views: 268

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33420

You can create your own hash by joining parameter_list with value_list and converting it to hash, and then pass it as the form data, like:

parameter_list = %w[from to foo]
value_list = %w[2005-01-01 2005-03-31 bar]

form_data = parameter_list.zip(value_list).to_h

p form_data
# {"from"=>"2005-01-01", "to"=>"2005-03-31", "foo"=>"bar"}
req.set_form_data form_data

Note a constraint is both arrays must have the same size.

Upvotes: 1

Related Questions