1
votes

I am playing around with nested hashes. Task:

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.

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.

3
parameter access key value pair params = { :father => "person1", :mother => ":person2", :child => "person3" } and access params[:father] give result "person1"Chaudhary Prakash
That is understood. It was passing more than one argument I was confused about.Coder_Sav

3 Answers

5
votes

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

0
votes

Use those variables names. Like below:

params = { :father => person1, :mother => person2, :child => person3 }
0
votes

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| %>