Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.ruby > #3517
| From | Brian Candler <b.candler@pobox.com> |
|---|---|
| Newsgroups | comp.lang.ruby |
| Subject | Re: Setting a 'reference' inside the method body |
| Date | 2011-04-26 10:28 -0500 |
| Organization | Service de news de lacave.net |
| Message-ID | <c8ea4e436f3d64ee1cc6891975d8e04c@ruby-forum.com> (permalink) |
| References | <ce11d8adf31eab2c2a5b15b2b4337a74@ruby-forum.com> <BANLkTim+1PkCGMWBqTk30M2QAtE-=wgVAA@mail.gmail.com> |
Xavier Noria wrote in post #995127:
> On Tue, Apr 26, 2011 at 4:55 PM, Peter Szinek <peter.szinek@gmail.com>
> wrote:
>
>> inside foo() we know whether we want to empty the array or not... it
>> would be complicated to return something from foo() with the current
>> architecture (based on which we could empty the hash or not).
>
> You cannot change the reference stored in the caller's baz, because
> Ruby has pass by value semantics. But hashes are mutable, in
> particular
>
> baz.clear
>
> wipes the hash, so the caller will see it empty as well.
(bar.clear that is). Using bar.replace({}) is another option. Both of
these mutate the Hash that was passed in.
In Ruby:
- all values are object references
- all method calls are pass-by-value
- a local variable is *not* itself an object
- you cannot take a "reference" to a local variable
Almost certainly you want to mutate the Hash being passed in, not
attempt to modify the caller's local variable which holds the reference
to that Hash.
That said, there is one nasty way to achieve specifically what you
asked:
def bar(b)
eval "baz='whoopee'", b
end
baz = {:fluff => :ork}
bar(binding)
p baz
It involves either passing a Binding (as shown), or passing a block,
which also carries a Binding, and then evaluating code in the context of
that Binding. Unless you're writing a debugger or something like that,
you almost certainly don't want to do this.
--
Posted via http://www.ruby-forum.com/.
Back to comp.lang.ruby | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Setting a 'reference' inside the method body Peter Szinek <peter.szinek@gmail.com> - 2011-04-26 09:55 -0500
Re: Setting a 'reference' inside the method body Xavier Noria <fxn@hashref.com> - 2011-04-26 10:04 -0500
Re: Setting a 'reference' inside the method body Brian Candler <b.candler@pobox.com> - 2011-04-26 10:28 -0500
Re: Setting a 'reference' inside the method body Charles Oliver Nutter <headius@headius.com> - 2011-04-27 00:46 -0500
Re: Setting a 'reference' inside the method body Robert Dober <robert.dober@gmail.com> - 2011-04-27 01:04 -0500
csiph-web