Nathaniel Rand Nathaniel Rand - 4 months ago 14
Ruby Question

Refactoring condition with a range of values

How might one refactor this bit of Ruby on Rails code?

def select_plan
unless params[:plan] && (params[:plan] == '1' || params[:plan] == '2' || params[:plan] == '3' || params[:plan] == '4' || params[:plan] == '5' || params[:plan] == '6' || params[:plan] == '7' || params[:plan] == '8')
flash[:notice] = "Please select a membership plan to register."
redirect_to root_url
end
end

Answer

I would do something like this.

def select_plan
  unless params[:plan].in?('1'..'8')
    flash[:notice] = "Please select a membership plan to register."
    redirect_to root_url
  end
end