Question

How to pass an instance variable as an argument to a function ? Example:

@tmp = "blabla"
...
my_function(@tmp)

@tmp should be "hello"

def my_function(foo)
foo = "hello"
end

Note: I changed the wording of the title !

Was it helpful?

Solution

@temp should not be "hello" the way you are doing it. If what you want to update @tmp I would change the way my_function works a bit:

def my_function
    'hello'
end

@tmp = "blabla"
...
@tmp = my_function

Ruby is a "pass by value" language. This might help explain it a bit better than I can: https://www.ruby-forum.com/topic/41160

Basically your my_function is only assigning foo "hello" while in the function, it then returns foo, but does not reassign the passed in object.

OTHER TIPS

Your question is somewhat under-specified, but it looks like you want to do some dynamic attribute assignment.

class Test
  attr_accessor :foo

  def initialize
    @foo = "asdf"
  end

  def my_function(var, set_to = "hello")
    self.instance_variable_set(var, set_to)
  end
end

usage:

t = Test.new # t.foo is "asdf"

t.my_function(:@foo) # t.foo is "hello"

t.my_function(:@foo, "bananas") # t.foo is "bananas"

Notably, you have to pass my_function a symbol representing your variable that you want to dynamically alter, not the variable itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top