Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError (String can't be coerced into Fixnum)?

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.

like image 769
Deekor Avatar asked Jul 18 '12 06:07

Deekor


1 Answers

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
like image 124
CrazyVipa Avatar answered Nov 15 '22 08:11

CrazyVipa