How would I loop over every instance variable "@anything" in a controller? I dont want to loop over one, I want to loop over them as a collection. Ideally scoped to the ones my controller method defines.
1 Answer
You can use instance_variables and instance_variable_get, e.g. like so:
@foo = 'Foo'
@bar = 'Bar'
instance_variables # => [:@foo, :@bar]
instance_variables.map(&method(:instance_variable_get))
# => ['Foo, 'Bar']
Ideally scoped to the ones my controller method defines.
Instance variables are scoped to instances, not methods. That's why they are called instance variables. And they aren't defined by methods, in fact, they aren't defined at all: they just spring into existence the first time they are assigned.
1 Comment
j_mcnally
instance_variables is what i was looking for, i knew about instance_variable_get, yeah i figured a method scope was asking alot. this is perfect thanks.