ehsan ehsan - 7 months ago 23
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 =
redirect_to(:action => 'index')

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

I mean we have defined
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?


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

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.