ハッシュから値を変更しようとすると奇妙な問題が発生します。設定は次のようになっています。
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: No implicit conversion of Symbol into Integer」というエラーが表示されますが、item[:company_name] の出力は期待される文字列です。何が間違っているのでしょうか?
ベストアンサー1
変数はインスタンス(形式内)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