Lukas Hoffmann
Lukas Hoffmann

Reputation: 607

Heroku Ruby NoMethodError string.capitalize

I use the following code to group locations depending on the first letter.

mobile_controller:

def index
  @locations = Location.all.group_by{|l| l.name[0].capitalize.match(/[A-Z]/) ? l.name[0].capitalize : "#"}
end

view:

<% @locations.keys.sort.each do |starting_letter| %>
  <%= starting_letter %>
  <% @locations[starting_letter].each do |location| %>
    <%= location.name %>        
  <% end %>
<% end %>

Everything works fine on my local machine, but heroku doesn't like it and keeps showing me this error:

NoMethodError (undefined method `capitalize' for 66:Fixnum):
app/controllers/mobile_controller.rb:13:in `search'
app/controllers/mobile_controller.rb:13:in `search'

How can I fix this?

Thanks in advance

Solution: Updated my Heroku Stack to Ruby 1.9.

Upvotes: 3

Views: 647

Answers (2)

Chowlett
Chowlett

Reputation: 46667

Under Ruby 1.8, String#[] returns the ASCII code of the referenced character rather than the character itself. Try l.name[0,1].capitalize in your controller.

Upvotes: 2

Dylan Markow
Dylan Markow

Reputation: 124419

Your local machine is probably on Ruby 1.9, and your Heroku app is running on 1.8.

In Ruby 1.8, calling String#[] will give you the character code (a number), whereas Ruby 1.9 will give you a string with the first character.

# Ruby 1.8
"test"[0]
# => 116

# Ruby 1.9
"test"[0]
# => "t"

You can use l.name[0..0] to get around this, or switch to a Ruby 1.9 stack on Heroku.

Upvotes: 5

Related Questions