TypeError(字符串不能强制转换为Fixnum)? [英] TypeError (String can't be coerced into Fixnum)?

查看:243
本文介绍了TypeError(字符串不能强制转换为Fixnum)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个奇怪的错误。我的应用程序在本地主机上运行得很好,但在我的Heroku服务器上出现此错误: 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 是数据库中的整数。



再次, 。让我知道你的想法。

删除 return 后, rep_score 方法工作正常。我对Ruby还是个新手,把 return 放在哪里是不对的?这是习惯于其他语言。

Ruby使用 + 作为组合工具为字符串和数学情况。

简单修正:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆