TypeError(字符串不能强制转换为Fixnum)? [英] TypeError (String can't be coerced into Fixnum)?
问题描述
TypeError(字符串不能强制转换为Fixnum):
以下是我的代码:
@rep = rep_score(@u)
根据引发错误的行的日志。我已经发表了评论,并将更改推向Heroku,现在应用运行良好。
以下是 rep_score
方法:
def rep_score(user)
rep = 0
user.badges.each do | b |
rep = rep + b.rep_bonus
end
return rep
end
rep_bonus
是数据库中的整数。
再次, 。让我知道你的想法。
从删除
方法工作正常。我对Ruby还是个新手,把 return
后, rep_score return
放在哪里是不对的?这是习惯于其他语言。
+
作为组合工具为字符串和数学情况。简单修正:
def rep_score(用户)
rep = 0
user.badges.each do | b |
rep = rep + b.rep_bonus.to_i
end
return rep
end
to_i
正在改变 rep_bonus
,这可能来自数据库模型,结果为一个整数。你可以设置几种不同的类型转换。举几个转换:
to_a
to_f
to_i
li>
to_s
I'm getting a weird error. My app runs perfectly fine on my localhost but on my Heroku server it's giving this error: TypeError (String can't be coerced into Fixnum):
Here is my code:
@rep = rep_score(@u)
According to the logs that's the line throwing the error. I've commented it out and pushed the changes to Heroku and the app runs fine now.
Here is the rep_score
method:
def rep_score(user)
rep = 0
user.badges.each do |b|
rep = rep + b.rep_bonus
end
return rep
end
Also rep_bonus
is an integer in the database.
Again this runs perfectly fine on localhost. Let me know what you think.
After removing return
from the rep_score
method it's working fine. I'm still new to Ruby, is there something wrong with putting return
? It's habit from other languages.
Ruby uses +
as a combination tool for strings AND mathematical situations.
Simple fix:
def rep_score(user)
rep = 0
user.badges.each do |b|
rep = rep + b.rep_bonus.to_i
end
return rep
end
to_i
is changing rep_bonus
, which is probably from the database model, from a string result into an integer. There are a few different typecasts you can set. To name a few conversions:
- Array:
to_a
- Float:
to_f
- Integer:
to_i
- String:
to_s
这篇关于TypeError(字符串不能强制转换为Fixnum)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!