我遇到一个奇怪的问题,当试图改变值从一个哈希。我有以下设置:
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到整数”,虽然item [:company_name]的输出是期望的字符串。我究竟做错了什么?
您的项变量保存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
http://stackoverflow.com/questions/21402111/typeerror-no-implicit-conversion-of-symbol-into-integer
本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:ruby-on-rails – TypeError:没有将Symbol隐式转换为Integer