Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking multiple params in Ruby

These params come out of html inputs in erb templates (this code is in the main application.rb), and I am checking if they are filled before I add them to n.requestusers, which will become part of a database entry. It works, but it feels more like a bash script the way it is now. What would be the best way to write something like this?

a route in the main .rb

if params[:user2].empty? && params[:user3].empty? && params[:user4].empty? && params[:user5].empty?
  n.requestusers = params[:user1]
elsif params[:user3].empty? && params[:user4].empty? && params[:user5].empty?
  n.requestusers = params[:user1], params[:user2]
elsif params[:user4].empty? && params[:user5].empty?
  n.requestusers = params[:user1], params[:user2], params[:user3]
elsif params[:user5].empty?
  n.requestusers = params[:user1], params[:user2], params[:user3], params[:user4]
else
  n.requestusers = params[:user1], params[:user2], params[:user3], params[:user4], params[:user5]
end
like image 591
jerius Avatar asked Sep 11 '26 02:09

jerius


1 Answers

Instead of having all of those conditional statements might you be interested in something like:

n.requestusers = params.select { |key, val| not val.empty? }.values

Or a cleaner way as suggested by @theTinMan:

n.requestusers = params.reject { |key, val| val.empty? }.values

select lets you take all of the none empty parameter values and returns them. values lets you grab those values as an array.

I am not experienced with web frameworks, so my suggestion is a bit of a shot in the dark.

like image 130
squiguy Avatar answered Sep 13 '26 14:09

squiguy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!