0

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 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.