0

I want to pass instance variables to a method, which then modifies them. This is because I have the same logic for different instance variables. Is this possible? I haven't got it working.

class A
    def update_ivar()
        update(@ivar)
    end
    
    def update(var)
       var = 1
    end
    
    def print_ivar()
        puts @ivar
        puts @ivar == nil
    end
end

a = A.new
a.update_ivar()
a.print_ivar()

Output


true
3
  • 1
    You don't need to pass instance variable. The very purpose of instance variable is use inside the methods which are inside the class. Commented Mar 23, 2022 at 4:10
  • @Rajagopalan I have the same logic for different instance vars, should I just create nearly identical methods were the only difference is the instance var being modified? Commented Mar 23, 2022 at 4:12
  • 3
    If you have the same logic for multiple pieces of data, then it is an indicator you need an Array, a Hash, or a similar container structure. You could do the same with instance variables, passing their name and looking them up using introspection, but that is an anti-pattern (less readable, less safe, and probably also less fast). Commented Mar 23, 2022 at 4:55

1 Answer 1

1

You can use instance_variable_set like this:

class A
  def update_ivar
    update(:@ivar) # Note the symbolized name here, it is not the variable itself
  end

 def update(var_name)
   instance_variable_set(var_name, 1)
 end

 def print_ivar
   puts @ivar
   puts @ivar == nil
 end
end

a = A.new
a.update_ivar  
a.print_ivar   
#=> 1
#=> false

I personally wouldn't like such a pattern because it leads to hard to read and understand code. But is it a code smell? That certainly depends on your application and your exact use case.

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

Comments

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.