Check for multiple parameters

I need to check for several parameters. I have currently written

if params[:p1].present? && params[:p2].present? && params[:p3].present? # Do something end 

Is there a more efficient way to do this?

+5
source share
2 answers

Can you use the Enumerable.all? method Enumerable.all? :

 %i( p1 p2 p3 ).all? { |key| params[key].present? } 

Another alternative, if you need values, is to select them and check for availability.

 params.values_at(*%i( p1 p2 p3 )).all?(&:present?) 

or

 params.values_at(:p1, :p2, :p3).all?(&:present?) 
+14
source

In Rails, you can use Hash#slice to find out if the required keys are present in the hash.

 # Below require is needed only in stand-alone program for testing purposes require 'active_support/core_ext/hash' params = {:p1=>"1", :p2=>"2", :p3 => "3", :p4=>"4"} mandatory_keys = [:p1, :p2, :p3] if (params.slice(*mandatory_keys).values.all?(&:present?) puts "All mandatory params present" else puts "Mandatory params missing" end 
0
source

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


All Articles