Reputation: 2392
I need to check the presence of multiple params. Currently what i have written is
if params[:p1].present? && params[:p2].present? && params[:p3].present?
# Do something
end
Is there a more efficient way to do this?
Upvotes: 9
Views: 4547
Reputation: 18762
In Rails, you can make use of Hash#slice
to figure out whether required keys are present in 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
Upvotes: 1
Reputation: 176552
You can use the Enumerable.all?
method:
%i( p1 p2 p3 ).all? { |key| params[key].present? }
Another alternative, if you need the values, it to fetch them and check the presence.
params.values_at(*%i( p1 p2 p3 )).all?(&:present?)
or
params.values_at(:p1, :p2, :p3).all?(&:present?)
Upvotes: 22