2011-05-22 86 views
19

我用這樣的方法:紅寶石 - 使用包括case語句

case referer 
     when (referer.include? "some_string") 
     redirect_link = edit_product_path 
     when (referer.include? "some_other_string") 
     redirect_link = other_product_path 
end 

不幸的是,這將返回零,即使串some_string出現在變量referer

這裏就是我試圖用Ruby控制檯:

ruby-1.8.7-p334 :006 > jasdeep = "RAILS" 
ruby-1.8.7-p334 :026 > case jasdeep 
ruby-1.8.7-p334 :027?> when (jasdeep.include? "AI") 
ruby-1.8.7-p334 :028?> puts "Hello" 
ruby-1.8.7-p334 :029?> end 
=> nil 

任何輸入將不勝感激。

回答

32

試試這個

jasdeep = "RAILS" 
case jasdeep 
when /IL/ 
    puts "Hello" 
end 
+0

按預期工作!謝謝! – 2011-05-22 00:19:27

+1

是否有可能在'when'布爾變量中做到這一點? – Nick 2012-04-17 18:22:42

+1

@Nick有可能: '''當/#{some_var}/ 放入「變量」 end''' – 2016-08-19 17:40:48

0

nil是puts語句的返回值,而不是.include ?.嘗試從控制檯單獨運行下面的兩個語句,並觀察返回值:

jasdeep.include? "AI" 

puts "hello" 
+0

'紅寶石1.8.7-P334:040>看跌期權「你好」 你好 =>無' – 2011-05-22 00:14:10

3
jasdeep = "RAILS" 

case 
    when jasdeep.include?("AI") 
    puts "Hello" 
end 
+0

感謝納什,但這並沒有幫助。 – 2011-05-22 00:21:03

1
case true 
when referer.include? "some_string" 
    redirect_link = edit_product_path 
when referer.include? "some_other_string" 
    redirect_link = other_product_path 
end 
+1

這導致Ruby 1.9.3出現'syntax error'(以及我想象的更高版本)。 – aceofbassgreg 2013-09-26 19:30:10