Ruby switch语句比较使用字符串和变量不起作用

时间:2013-11-25 16:18:08

标签: ruby-on-rails string comparison switch-statement

我在控制器中启动了一些变量,如此

 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"

然后我尝试在我的switch语句中使用它们,如下所示:


 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

为什么会这样?我认为它与对象比较有关。但是如何使用变量使其工作?

感谢。

1 个答案:

答案 0 :(得分:2)

使用尾随逗号定义常量,这很糟糕,因为它将['1', '2', '3', '4', '5']数组赋值给UPLOAD_N_DATA常量。它应该是:

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