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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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,
verbis not in scope (because it was defined outside of the method whereverblives).Besides the eval-binding hack mentioned by stephenjudkins, there are two ways to do what you want. One is just to assign
verb: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:
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.