Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: no implicit conversion of Symbol into Integer

I encounter a strange problem when trying to alter values from a Hash. I have the following setup:

myHash = {
  company_name:"MyCompany", 
  street:"Mainstreet", 
  postcode:"1234", 
  city:"MyCity", 
  free_seats:"3"
}

def cleanup string
  string.titleize
end

def format
  output = Hash.new
  myHash.each do |item|
    item[:company_name] = cleanup(item[:company_name])
    item[:street] = cleanup(item[:street])
    output << item
  end
end

When I execute this code I get: "TypeError: no implicit conversion of Symbol into Integer" although the output of item[:company_name] is the expected string. What am I doing wrong?

like image 595
Severin Avatar asked Jan 28 '14 09:01

Severin


2 Answers

Your item variable holds Array instance (in [hash_key, hash_value] format), so it doesn't expect Symbol in [] method.

This is how you could do it using Hash#each:

def format(hash)
  output = Hash.new
  hash.each do |key, value|
    output[key] = cleanup(value)
  end
  output
end

or, without this:

def format(hash)
  output = hash.dup
  output[:company_name] = cleanup(output[:company_name])
  output[:street] = cleanup(output[:street])
  output
end
like image 139
Marek Lipka Avatar answered Oct 20 '22 14:10

Marek Lipka


This error shows up when you are treating an array or string as a Hash. In this line myHash.each do |item| you are assigning item to a two-element array [key, value], so item[:symbol] throws an error.

like image 17
BroiSatse Avatar answered Oct 20 '22 15:10

BroiSatse