Reputation: 31
I am playing around with nested hashes. Task:
Create three hashes called
person1
,person2
, andperson3
, with first and last names under the keys:first
and:last
. Then create a params hash so thatparams[:father]
isperson1
,params[:mother]
isperson2
, andparams[:child]
isperson3
. Verify that, for example,params[:father][:first]
has the right value.
My solution:
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" }
then params[:father][:first]
gives
TypeError: no implicit conversion of symbol into Integer
Why? I don't understand why I get the TypeError.
Upvotes: 1
Views: 18076
Reputation: 6565
The reason I was getting this error was the following...
Instead of doing this
<%= form.fields_for :terms, term do |term_form| %>
I was doing this...
<%= form.fields_for :terms_attributes, term do |term_form| %>
Upvotes: 0
Reputation: 5155
When you assign values to the params
hash keys, you supply strings instead of personx
hashes. The proper way would be instead of
params = { :father => ":person1"...
do
params = { :father => person1...
The reason for the error is as follows. This line:
params[:father][:first]
fetches the value of params[:father]
first. You expect this value to be a hash, but due to the syntax error above it is a string. String
does implement []
method just like hash but its semantics is different. It accesses a character within a string by its integer index. It expects the index to be passed as an argument to []
.
Since you pass a symbol instead, [:first]
, and there is no default way to convert a symbol to integer, you get the appropriate error:
TypeError: no implicit conversion of symbol into Integer
Upvotes: 6
Reputation: 118299
Use those variables names. Like below:
params = { :father => person1, :mother => person2, :child => person3 }
Upvotes: 0