ben
ben

Reputation: 29817

Why am I getting this TypeError - "can't convert Symbol into Integer"?

I have an array of hashes. Each entry looks like this:

- !map:Hashie::Mash 
  name: Connor H Peters
  id: "506253404"

I'm trying to create a second array, which contains just the id values.

["506253404"]

This is how I'm doing it

second_array = first_array.map { |hash| hash[:id] }

But I'm getting this error

TypeError in PagesController#home
can't convert Symbol into Integer

If I try

second_array = first_array.map { |hash| hash["id"] }

I get

TypeError in PagesController#home
can't convert String into Integer

What am I doing wrong? Thanks for reading.

Upvotes: 3

Views: 3092

Answers (2)

stef
stef

Reputation: 14268

This sounds like inside the map block that hash is not actually a hashie - it's an array for some reason.

The result is that the [] method is actually an array accessor method and requires an integer. Eg. hash[0] would be valid, but not hash["id"].

You could try:

first_array.flatten.map{|hash| hash.id}

which would ensure that if you do have any nested arrays that nesting is removed.

Or perhaps

first_array.map{|hash| hash.id if hash.respond_to?(:id)}

But either way you may end up with unexpected behaviour.

Upvotes: 0

vonconrad
vonconrad

Reputation: 25387

You're using Hashie, which isn't the same as Hash from ruby core. Looking at the Hashie github repo, it seems that you can access hash keys as methods:

first_array.map { |hash| hash.id }

Try this out and see if that works--make sure that it doesn't return the object_id. As such, you may want to double-check by doing first_array.map { |hash| hash.name } to see if you're really accessing the right data.

Then, provided it's correct, you can use a proc to get the id (but with a bit more brevity):

first_array.map(&:id)

Upvotes: 6

Related Questions