Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 1016 Vote(s) - 3.51 Average
  • 1
  • 2
  • 3
  • 4
  • 5
'pass parameter by reference' in Ruby?

#1
In Ruby, is it possible to pass by reference a parameter with value-type semantics (e.g. a Fixnum)?
I'm looking for something similar to C#'s '**ref**' keyword.

Example:

def func(x)
x += 1
end

a = 5
func(a) #this should be something like func(ref a)
puts a #should read '6'

Btw. I know I could just use:

a = func(a)

Reply

#2
However, it seems that composite objects, like hashes, are passed by reference:

fp = {}
def changeit(par)
par[:abc] = 'cde'
end

changeit(fp)

p fp

gives

{:abc=>"cde"}
Reply

#3
You can try following trick:

def func(x)
x[0] += 1
end

a = [5]
func(a) #this should be something like func(ref a)
puts a[0] #should read '6'

Reply

#4

[To see links please register here]


> Fixnum objects have immediate value. This means that when they are assigned or
passed as parameters, the actual object is passed, rather than a reference to
that object.

Also [Ruby is pass by value][1].


[1]:

[To see links please register here]

Reply

#5
Ruby doesn't support "pass by reference" at all. Everything is an object and the references to those objects are always passed by value. Actually, in your example you are passing a copy of the reference to the `Fixnum` Object by value.

The problem with the your code is, that `x += 1` doesn't modify the passed `Fixnum` Object but instead creates a completely new and independent object.

I think, Java programmers would call `Fixnum` objects **immutable**.
Reply

#6
You can accomplish this by explicitly passing in the current binding:

def func(x, bdg)
eval "#{x} += 1", bdg
end

a = 5
func(:a, binding)
puts a # => 6
Reply

#7
In Ruby you can't pass parameters by reference. For your example, you would have to return the new value and assign it to the variable a or create a new class that contains the value and pass an instance of this class around. Example:

class Container
attr_accessor :value
def initialize value
@value = value
end
end

def func(x)
x.value += 1
end

a = Container.new(5)
func(a)
puts a.value

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through