-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1


On Apr 8, 2008, at 6:08 PM, Infinit Blue wrote:
> For example I hv the following code:
>
> def test
>  n = 1
>  yield(n)
>  puts n
> end
>
> --------
> test {|x| x = x + 1; puts x}
>
> the output is:
> 2
> 1
>
> How can I modify the parameter x in block?
>
> Appreciate for your help.
> --  
> Posted via http://www.ruby-forum.com/.
>

Hi,

actually, something like this code would work if you would use a  
'real' object:

- -----
class A
   attr_accessor :name
end

def test
   a = A.new
   a.name = "foo"
   yield(a)
   puts a.inspect
end

test {|x| x.name = "bar" }
#=> a.name is "bar"
- -----


But, if you reassign b with a new object, this will not work:

- -----
class A
   attr_accessor :name
end

def test
   a = A.new
   a.name = "foo"
   yield(a)
   puts a.inspect
end
test {|x| x = A.new; x.name = "bar" }
- -----

The first example changes x "in place", while the second operates on a
totally different x.

Fixnums in Ruby are so called "immediate objects" and do show
subtle differences in their behaviour. They are immutable (there
is only one 1), so 1+1 is a different object. This makes it impossible
to change the value of a Fixnum in place. (This is - by the way - the
reason why i++ does not work in ruby)

As you are not able to do that, it is impossible to "modify"
a fixnum parameter. (because you only option is reassigning)

Because of this, i would not talk about "modifying the parameter" but  
about
"modifying the internal state of a parameter".

Regards,
Florian Gilcher
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (Darwin)

iEYEARECAAYFAkf7nY4ACgkQJA/zY0IIRZZsGACeJ1Qs3jCO4NzrXQ2q9xDqbdmg
fwgAoKZa8vntAoF6EU0uDsQ1m45lUpz7
=ijgh
-----END PGP SIGNATURE-----