0

given the following code:

vars = instance_variables.map(&method(:instance_variable_get))
vars.each {|v| v = 123}

would that set @something = 123?

taking it a step further

is it the same if i have

vars = instance_variables.map(&method(:instance_variable_get))
vars.each {|v| doSomething(v) }

def doSomething(var)
  var = 123
end

how would i mutate var from inside a function?

1
  • Can you clarify what you're wanting to achieve, it's generally bad practice to change the value of a parameter, and in many cases not easily possible without a bit of a hack. Commented Oct 19, 2012 at 22:02

2 Answers 2

1

You can test this in irb pretty quickly:

@something = 456
instance_variables
# => [:@something]
instance_variables.map(&method(:instance_variable_get)).each { |v| v = 123 }
@something
# => 456 (i.e. "didn't mutate @something")

def doSomething(var)
  var = 123
end
vars = instance_variables.map(&method(:instance_variable_get))
vars.each { |v| doSomething(v) }
@something
# => 456 (i.e. "didn't mutate @something")

Object#instance_variable_set, however, does change the value of @something:

@something = 456
instance_variables.each { |v| instance_variable_set(v, 123) }
@something
# => 123
Sign up to request clarification or add additional context in comments.

4 Comments

but i'd also need to pass the key? for v and by key i mean instance var name?
Yeah, v in that last snippet is a symbol: :@something
To be precise, your approach still doesn't mutate the instance variable. It just sets it to a new value. When you say "mutate", generally people mean to change some aspect of an existing object without assigning a new one, i.e by preserving the object_id of the referenced object.
@HolgerJust: Really good point! Edited the answer to be more precise.
1

Agreeing with pje, you probably should have tested this in irb, but I'm assuming you want to capture a setter for every instance variable, so I'd recommend something like:

setters = instance_variables.map{|v| lambda { |val| instance_variable_set(v, val) }}

then you can just do setters[0].call(__VALUE__) and it will set the value accordingly.

What is it you are trying to achieve?

2 Comments

it wasnt so much laziness, just curiousity of what the implications of why / how the pass through works etc.
i didn't really know about the mutations / instance_variable_set etc. I'll update my question to reflect more of that request for knowledge.

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.