2011-11-08 48 views
0

錯誤使用Ruby異常

result = ["true","false","false","false"] 

這樣定義的數組,在我的代碼通過遍歷數組,並拋出一個異常時,我遇到錯誤。

begin result.each do |method| 
      raise if (method == false) { 
      rescue Exception => Form_Validation_Failure 
        puts "fail!" 
      end } 
     end 

當我執行代碼時出現錯誤。這是在Ruby中引發異常的正確方法嗎?請有人幫助這個請。

乾杯!

回答

4

除了在你的比較中使用數組中的字符串和常量false之外,我還看到了大括號內的救援。

我認爲你正在尋找代碼的形式是:

>> result = [true,false,true,false] 
=> [true, false, true, false] 
>> 
?> result.each do |method| 
?> begin 
?>  raise if not method # preferred to method == false 
>>  puts "ok" 
>> rescue 
>>  puts "fail!" 
>> end 
>> end 
ok 
fail! 
ok 
fail! 
=> [true, false, true, false] 
+0

感謝雷!這就是我一直在尋找:) – verdure

+0

它通常也是壞形式使用'==假'或'==真正'。這是一個布爾值,只是說'除非方法'或'如果!方法' – DGM

+0

O noes you got me!我曾數千次謾罵過。必須......改變......答案...... –

0

你應該在比較中使用的字符串:

... 
raise if (methods == "false") { 
... 

Ruby有所有的一切都真實的對象,所以與價值"false"和布爾值false字符串之間的差異。