Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change the original variable from a ruby block? [duplicate]

Tags:

ruby

Possible Duplicate:
'pass parameter by reference' in Ruby?

in this example:

def test
  verb = 'nothing'
  yield verb
  puts verb
end

test {|verb| verb = 'something'}

it will print "nothing".

is it possible to change it to "something"?

thanks

like image 784
never_had_a_name Avatar asked Jul 16 '10 20:07

never_had_a_name


1 Answers

You have to remember, variables in Ruby are just references to objects. Each reference is independent of any other reference, though they may refer to the same object.

The other thing to remember is the the scope of a block is the scope it was defined in. So for your block, verb is not in scope (because it was defined outside of the method where verb lives).

Besides the eval-binding hack mentioned by stephenjudkins, there are two ways to do what you want. One is just to assign verb:

def test
  verb = 'nothing'
  verb = yield verb
  puts verb
end

This pretty directly does what you want and is really the best way to go about it.

The other way is to directly mutate the object that's passed in:

test {|verb| verb.replace 'something'}

I don't recommend this, though, because it actually changes the string itself instead of just assigning a new string to the variable. So other places where the same string object is referenced, it will contain the new text. This isn't a problem in your example, but it's a massive bug waiting to happen in any real program.

like image 107
Chuck Avatar answered Oct 19 '22 08:10

Chuck