Reputation: 341
def get_dept_class_type
departments, classifications, types = [["-- select one --"]] * 3
Department.all.each do |d|
departments << d.name
end
Classification.all.each do |c|
classifications << c.name
end
Type.all.each do |t|
types << t.name
end
return departments, classifications, types
end
def new
@departments, @classifications, @types = get_dept_class_type
end
Hello guys,
above is my code in Ruby to assign the return values from "get_dept_class_type" function to "def new" instance variables. The problem is, the return values from the "get_dept_class_type" function were not extracted, So all instance variables have the same values. Each instance variable is the containing value of a select tag in html form.
The values of department, classification, type select tags have these the same content:
Please it help me to figure this out. Thank you in advanced.
Upvotes: 1
Views: 95
Reputation: 118271
Your main problem is -
departments, classifications, types = [["-- select one --"]] * 3
changed it to -
departments, classifications, types = Array.new(3) { ["-- select one --"] }
Lets debug it :-
([[]] * 3).map(&:object_id) # => [72506330, 72506330, 72506330]
but
Array.new(3) { [] }.map(&:object_id) # => [76642680, 76642670, 76642520]
You can see, that all the inner objects are basically same object. Basically you have created an array of array, say a
, where all the element arrays are same object. Thus if you have modified, say a[0]
, you can see the same change when you would inspect a[1]
or a[2]
. But if you do create the same array of array, a
as , Array.new(3) { [] }
, then each inner element array of a
, will be different object. Thus if you say modify a[0]
, then a[1]
and a[2]
will be intact.
Worth to read Common gotchas
.
Upvotes: 3