开发者

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:

&开发者_C百科lt;% @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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜