How to modify the param value in block

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.

On Apr 8, 12:08 pm, Infinit B. [email protected] wrote:

the output is:
2
1

How can I modify the parameter x in block?

Appreciate for your help.

Posted viahttp://www.ruby-forum.com/.

[email protected]:~$ irb
irb(main):001:0> def test
irb(main):002:1> n = 1
irb(main):003:1> n = yield(n)
irb(main):004:1> puts n
irb(main):005:1> end
=> nil
irb(main):006:0> test {|x| x += 1; puts x; x }
2
2
=> nil

[email protected]:~$ irb
irb(main):001:0> def test
irb(main):002:1> n = 1
irb(main):003:1> n = yield(n)
irb(main):004:1> puts n
irb(main):005:1> end
=> nil
irb(main):006:0> test {|x| x += 1; puts x; x }
2
2
=> nil

how can I force x pass by ref ? then I can change the value of x in the
block and no need to hv a return value and assign statement.

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

On Apr 8, 2008, at 6:08 PM, Infinit B. wrote:

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 G.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (Darwin)

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

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 G.

Got it. Thanks for your great inside explanation!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs