TypeError: can't convert String into Integer

Posted by demas on Stack Overflow See other posts from Stack Overflow or by demas
Published on 2010-03-21T09:42:29Z Indexed on 2010/03/21 9:51 UTC
Read the original article Hit count: 560

Filed under:

I have code:

class Scene
  def initialize(number)
    @number = number
  end
  attr_reader :number
end

scenes = [Scene.new("one"), Scene.new("one"), Scene.new("two"), Scene.new("one")]

groups = scenes.inject({}) do |new_hash, scene|
   new_hash[scene.number] = [] if new_hash[scene.number].nil?
   new_hash[scene.number] << scene
end

When I'm lauching it I get error:

freq.rb:11:in `[]': can't convert String into Integer (TypeError)
       from freq.rb:11:in `block in <main>'
       from freq.rb:10:in `each'
       from freq.rb:10:in `inject'
       from freq.rb:10:in `<main>'

If I change scenes to:

scenes = [Scene.new(1), Scene.new(1), Scene.new(2), Scene.new(1)]

the problem dissapear.

Why I get error message in the first case? Why Ruby decide to convert scene.number from String to Integer?

And one additional question about the 'inject' method. When Ruby initialize the 'new_hash' variable and how can Ruby know the type of this variable?

© Stack Overflow or respective owner

Related posts about ruby