TypeError:没有将Symbol隐式转换为Integer

时间:2014-01-28 09:50:39

标签: ruby-on-rails ruby

尝试从Hash中更改值时遇到一个奇怪的问题。我有以下设置:

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

当我执行此代码时,我得到:“TypeError:没有将Symbol隐式转换为Integer”,尽管item [:company_name]的输出是预期的字符串。我做错了什么?

5 个答案:

答案 0 :(得分:43)

您的item变量包含Array个实例([hash_key, hash_value]格式),因此在Symbol方法中不会指望[]

您可以使用Hash#each

来完成此操作
def format(hash)
  output = Hash.new
  hash.each do |key, value|
    output[key] = cleanup(value)
  end
  output
end

或者,没有这个:

def format(hash)
  output = hash.dup
  output[:company_name] = cleanup(output[:company_name])
  output[:street] = cleanup(output[:street])
  output
end

答案 1 :(得分:11)

当您将数组或字符串视为哈希时,会显示此错误。在此行myHash.each do |item|中,您将item分配给双元素数组[key, value],因此item[:symbol]会引发错误。

答案 2 :(得分:3)

你可能意味着这个:

require 'active_support/core_ext' # for titleize

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

def cleanup string
  string.titleize
end

def format(hash)
  output = {}
  output[:company_name] = cleanup(hash[:company_name])
  output[:street] = cleanup(hash[:street])
  output
end

format(myHash) # => {:company_name=>"My Company", :street=>"Mainstreet"}

请阅读Hash#each

上的文档

答案 3 :(得分:2)

myHash.each{|item|..}返回item迭代变量的数组对象,如下所示: -

[:company_name, "MyCompany"]
[:street, "Mainstreet"]
[:postcode, "1234"]
[:city, "MyCity"]
[:free_seats, "3"]

你应该这样做: -

def format
  output = Hash.new
  myHash.each do |k, v|
    output[k] = cleanup(v)
  end
  output
end

答案 4 :(得分:0)

我在工作中遇到了很多次,发现一个简单的解决方法是按类询问数组元素是否为哈希。

if i.class == Hash

    notation like i[:label] will work in this block and not throw that error

end
相关问题