Forum: Ruby How to pass numeric variables by reference?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
3fd17cac06aeb4d0b087b1b0c7a94c73?d=identicon&s=25 Eric Christensen (ericrchr)
on 2005-12-09 05:23
What's the Ruby way of achieving pass-by-reference for numbers, as in
the C code

void foo (int* x)
{

}
15bd00b1919f3f2920dc70da19c1ead9?d=identicon&s=25 rubikitch (Guest)
on 2005-12-09 05:42
(Received via mailing list)
From: Eric Christensen <ericrchr@gmail.com>
Subject: How to pass numeric variables by reference?
Date: Fri, 9 Dec 2005 13:23:36 +0900

> What's the Ruby way of achieving pass-by-reference for numbers, as in
> the C code

Array can do it.

def f(a)
  a[0] = 10
end

a = [1]
f(a)
a[0] == 10 or raise
puts "ok"
Ce60c4f78a63b0695e4dafc4bd7964f7?d=identicon&s=25 vanek (Guest)
on 2005-12-09 13:20
(Received via mailing list)
probably assign on callback. In other words, Ruby doesn't have
a direct pass-by-reference operation for numbers,
but you can easily achieve the same result.

using irb:

  10 :> def foo(c,d)
return c+1, d+2
end
     ==> nil
  13 :> a,b = 5,6
     ==> [5, 6]
  14 :> puts a,b
5
6
     ==> nil
  15 :> a,b = foo(a,b)
     ==> [6, 8]
  16 :> puts a,b
6
8
This topic is locked and can not be replied to.