I'd like to know if there is a simpler way to do these 2 conditions in ruby :
if params[:action] == 'index' || params[:action] == 'show'
and
开发者_如何学编程if !(comment = (session[:my_params].include?(:comment) rescue nil)).nil?
Thanks in advance
For the first one, you could do:
if %w(index show).include?(params[:action])
The second should really be re-factored into two lines: assignment within a condition check is a code smell; there's never a reason for it.
If you're using Rails / ActiveSupport, you can take advantage of Object#try
comment = session[:my_params].try(:include?, :comment)
if comment
# ... comment is in scope
end
Otherwise, you're left with something slightly clunkier:
comment = session[:my_params].include?(:comment) rescue nil
if comment
# etc
1:
if ['index','show'].include? params[:action]
2:
if (comment = (session[:my_params].include?(:comment) rescue nil))
!
and .nil?
in second condition are redundant
But, really, you should not try to make everything as short as possible, the first thing to care about is how clear your code would be for other people. The second condition should look like:
if ( comment = (session[:my_params] && session[:my_params].include?(:comment) )
or even
comment = session[:my_params] && session[:my_params].include?(:comment)
if comment
First one can be refractored like this:
if ['index', 'show'].include? params[:action]
or
if %w(index show).include? params[:action]
This should be faster than using an array and include?
:
case params[:action]; when 'index', 'show'
...
end
The second one:
if comment = (session.fetch(:my_params, {}).include?(:comment))
精彩评论