ehsan ehsan - 4 months ago 8
Ruby Question

Are we allowed to define more than one instance variables with the same name in ruby?

Why is below code valid ?

#Both actions are in the same Controller
def create
@subject = Subject.new(subject_params)
if @subject.save
redirect_to(:action => 'index')
else
render('new')
end
end

def delete
@subject = Subject.find(params['id'])
end


I mean we have defined
@subject
two times, isn't it going to get mixed up or have I just misunderstand this
intance variable
definition in ruby with the one in Java?

Answer

We do not have @subject defined twice. It’s being assigned to different values, in different methods.

That said, when the method #delete is being called, @subject takes a value of Subject.find(params['id']) and when #new is called, it becomes Subject.new(subject_params).

I am unsure why it looks suspicious to you. Methods #create and #delete in Rails are rarely called subsequently, but even if they were, in non pure functional languages it’s totally legit to reassign variables values.