2016-08-05 2 views
-1

私はネストされたハッシュで遊んでいます。タスク:TypeErrorを取得するのはなぜですか:シンボルをIntegerに暗黙的に変換しませんか?

Create three hashes called person1 , person2 , and person3 , with first and last names under the keys :first and :last . Then create a params hash so that params[:father] is person1 , params[:mother] is person2 , and params[:child] is person3 . Verify that, for example, params[:father][:first] has the right value.

私のソリューション:その後、

person1 = {first: "first_name1", last: "last_name1"} 
person2 = {first: "first_name2", last: "last_name2"} 
person3 = {first: "first_name3", last: "last_name3"} 
params = { :father => ":person1", :mother => ":person2", :child => ":person3" } 

params[:father][:first]

TypeError: no implicit conversion of symbol into Integer

なぜを与えますか?私はなぜTypeErrorを取得するのか分からない。

+0

パラメータをアクセスキーと値のペアのparams = {:父=> "person1"、:mother => ":person2"、:child => "person3"}とアクセスするparams [:father]結果 "person1" –

+0

これは分かります。私は混乱していた複数の議論を通過していました。 – Savina10

答えて

3

、あなたは、文字列の代わりに、personxハッシュを供給しています。適切な方法は、以下のようにエラーの理由がある

params = { :father => person1... 

を行う代わりに

params = { :father => ":person1"... 

だろう。この行:

params[:father][:first] 

は、最初にparams[:father]の値を取得します。この値がハッシュであると予想しますが、上の構文エラーのために文字列があります。 Stringは、ハッシュのように[]メソッドを実装しますが、そのセマンティクスは異なります。整数インデックスで文字列内の文字にアクセスします。インデックスが[]への引数として渡されることを期待しています。

あなたの代わりに、[:first]記号を渡すと、整数へのシンボルに変換するデフォルトの方法はありませんので、あなたが適切なエラーを取得:

TypeError: no implicit conversion of symbol into Integer

+0

なんらかの理由で、私は構文について混乱した文字列 ""でした。今、私は分かる。 – Savina10

0

これらの変数名を使用します。以下のように:あなたはparamsハッシュキーに値を割り当てると

params = { :father => person1, :mother => person2, :child => person3 } 
関連する問題