簡體   English   中英

Ruby內聯開始和救援無法正常執行

[英]Ruby inline begin and rescue not performing properly

我有以下代碼

'Performance' => {
    'Date' => performance_values.date.strftime('%m/%d/%Y'),
    'Ratio' => begin sprintf("%0.02f", performance_values.ratio) rescue nil end},
'Ratings' => {
    'Overall' => performance_values.overall_rating,
    '3-yr' => performance_values.3yr_rating}

使用“比率”有時可能為零,因此我嘗試從sprintf函數開始/進行救援,而將其設為零。

當此命令運行並且performance_values.ratio為nil時,我收到以下錯誤消息:

TypeError: can't convert nil into Float

內聯,您無需指定beginend Rails知道您正在救援整條生產線。

嘗試這個:

'Performance' => {
    'Date' => performance_values.date.strftime('%m/%d/%Y'),
    'Ratio' => (sprintf("%0.02f", performance_values.ratio) rescue nil)},
'Ratings' => {
    'Overall' => performance_values.overall_rating,
    '3-yr' => performance_values.3yr_rating}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM