banditKing
banditKing

Reputation: 9579

Ruby switch statement comparison using a string and a variable not working

I have initiated some variables in my controller like so

 class ServicesController < ApplicationController
   before_action :set_service, only: [:show, :edit, :update, :destroy]
UPLOAD_N_DATA = "1", 
UPLOAD_T_DATA = "2", 
UPLOAD_C_DATA = "3", 
UPLOAD_E_DATA = "4",
UPLOAD_V_DATA = "5"

Then Im trying to use these in my switch statement like so:


 DOESNT WORK:


 # GET /services/1
 # GET /services/1.json
  def show
puts "Service Id received = #{params[:id]} of class #{params[:id].class}"
case(params[:id])
    when UPLOAD_N_DATA
        puts "Service to upload N Data evoked"
    when UPLOAD_T_DATA
        puts "Service to upload T Data evoked"
    when UPLOAD_C_DATA
        puts "Service to upload C Data evoked"
    when UPLOAD_E_DATA
        puts "Service to upload E Data evoked"
    when UPLOAD_V_DATA
        puts "Service to upload V Data evoked"
    else
        puts "Error in Service Controller Show Services.\n Unknown Service Requested"
end
   end

   THIS WORKS:

   # GET /services/
   # GET /services/1.json
   def show
puts "Service Id received = #{params[:id]} of class #{params[:id].class}"
case(params[:id])
    when "1"
        puts "Service to upload N Data evoked"
    when "2"
        puts "Service to upload T Data evoked"
    when "3"
        puts "Service to upload C Data evoked"
    when "4"
        puts "Service to upload E Data evoked"
    when "5"
        puts "Service to upload C Data evoked"
    else
        puts "Error in Service Controller Show Services.\n Unknown Service Requested"
end
   end

Why is this happening? I think its something to do with object comparisons. But How to make it work using variables?

Thanks.

Upvotes: 0

Views: 270

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51171

You define your constant with trailing commas, which is bad, because it assigns ['1', '2', '3', '4', '5'] array to UPLOAD_N_DATA constant. It should be:

UPLOAD_N_DATA = "1"
UPLOAD_T_DATA = "2"
UPLOAD_C_DATA = "3"
UPLOAD_E_DATA = "4"
UPLOAD_V_DATA = "5"

Upvotes: 2

Related Questions