Writing destructive functions

M

Martin

How would I make something like this do what I want it to?
----
def foo!(a)
a = "bar"
return "baz"
end

change_me = "hello"
some_var = foo!(change_me)

puts change_me #=> "bar"
puts some_var #=> "baz"
 
M

Martin DeMello

Martin said:
How would I make something like this do what I want it to?
----
def foo!(a)
a = "bar"
return "baz"
end

change_me = "hello"
some_var = foo!(change_me)

puts change_me #=> "bar"
puts some_var #=> "baz"

The short answer is that you can't - variables themselves are not
objects, so you can't pass a variable to a function and have it rebind
it to another object. What you *can* do is change the contents of the
object that you pass in to the function. Your class needs to define a
'replace' method, so that you can say

def foo!(a)
a.replace('bar')
return 'baz'
end

Hash, Array and String have replace methods defined for them, so your
client code should work as written.

martin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,072
Latest member
trafficcone

Latest Threads

Top