0

I have a hash (the real one is much bigger)

parsed = {"follower_count" => 500, "something_else" => "etc", "xyz" => "abc"}

and a class hanging around that looks like this

 class Company
   attr_accessor :followers

   def initialize(thehash)
      @followers = thehash['follower_count']
   end
 end

So lastly there is this code which throws the error before I can worry about anything else going wrong

>> parsed.map {|t| Company.new(t)}
TypeError: can't convert String into Integer
  from (irb):7:in `[]'
  from (irb):7:in `initialize'
  from (irb):12:in `new'
  from (irb):12
  from (irb):12:in `map'
  from (irb):12:in `each'
  from (irb):12:in `map'
  from (irb):12
0

2 Answers 2

3

When you iterate over a Hash, the block gets an array as its argument and that array contains (in order) the key and value for one pair in the Hash. So, in here:

parsed.map { |t| ... }

t is actually a two element array and is usually written:

parsed.map { |k, v| ... }

Then, inside Company#initialize, you're treating t as a Hash when it is actually a two element Array.

You don't want to use map on parsed at all, you just want to Company.new(parsed).

Sign up to request clarification or add additional context in comments.

Comments

2

When you use map on a hash, you should use two variables in the block:

parsed.map {|k,v| .. use k and v here .. }

It doesn't seem like you want to iterate over parsed at all, you want to use it as the argument to Company.new:

Company.new(parsed)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.