2014-02-21 55 views
3

我已经创建了一个迭代Order对象数组的类方法。我使用那里的数据来构建一个哈希。我的一个,如果迭代里面块是:Ruby If .. Else .. End/Increment:语法错误

if !(report_hash[user_id][reason]) 
    report_hash[user_id][reason] = 1 
else 
    report_hash[user_id][reason]++ 
end 

当我运行这个方法,我得到:

.rb:66 syntax error, unexpected keyword_end (SyntaxError) 

66号线是end生活在那里。为什么Ruby不期望在这个块的最后有一个结束语句?一旦一切正常,我打算将所有的条件逻辑转换成单独的类方法,但我一直在试图弄清楚这一点,并且有点卡住了。

回答

6

增量法++是不是在Ruby中法律,使用+= 1代替:

if !(report_hash[user_id][reason]) 
    report_hash[user_id][reason] = 1 
else 
    report_hash[user_id][reason] += 1 
end 

有点起色(代码大小):我会将此代码重构为以下内容:

report_hash[user_id][reason] ||= 1 # this will set report_hash[user_id][reason] to 1 if it is nil 
report_hash[user_id][reason] += 1 
+0

嗯,我可以发誓我抬头看着Ruby增加,发现这个运算符。我想增加任何附加到每个用户ID的原因关键字的值,所以我想像像'report_hash [user_id] [reason] + = report_hash [user_id] [reason]' –

+0

嗯我不明白你的评论@ ChrisClouten ...你可以用其他词语尝试吗?也许有一个例子? – MrYoshiji

+0

所以如果report_hash [user_id] [reason]不是零,我想增加一个当前值。我认识你的例子,我认为我刚刚在+ = 1. –

1

Ruby没有++运算符。相反,你应该有:

report_hash[user_id][reason] += 1