Functions and arrays (ruby)

Soldato
Joined
24 Nov 2002
Posts
16,378
Location
38.744281°N 104.846806°W
Is it possible to access a function defined/filled array from outside the function?

e.g.

Code:
def foo()
 arr = [blah blah blah]
end

foo()

puts arr
 
I'm not really au fait with ruby, but to do this in another language you would normally have to make the arr variable global or return it as a public variable inside the function.
 
JonB said:
I'm not really au fait with ruby, but to do this in another language you would normally have to make the arr variable global or return it as a public variable inside the function.
I've read that to do the former was bad so was looking for an alternative....

Referring it as a public inside isn't really an option so I've settled for a global var for now before I rewrite the blasted thing.
 
global variables suck! :p

Can you define the array in the function that calls the other function? Pass it in empty, it gets filled and returned.

I don't really know much about ruby either, but in other languages you would pass the empty array item as a parameter to the filling function, I don't know how you define parameters in ruby.

def foo(arr[])
arr = [blah blah blah]
return arr
end

foo(arr[])
puts arr


in pseudocode:

Code:
void Function fillArray(ArrayClass &arrayitem)
{
 arrayitem = {1,2,3,4 };
}

void Function Main()
{
 ArrayClass arrayitem;
 fillArray(arrayitem);
}
 
Last edited:
Code:
function foo()
{
 $arr = array('blah' => 'blah', 'blah2' => 'blah2');
 return $arr
}

$arr = foo();

echo $arr['blah']

If it's any use, that's how I would do it in php.
 
The problem is my function does a few things so I can't call it as above.

I'll just have to use global arrays ... or rewrite.
 
jdickerson said:
The problem is my function does a few things so I can't call it as above.

I'll just have to use global arrays ... or rewrite.

you can use the return statement however just it's not required. Just return the array at the end.
 
Hi,

If you need to return multiple objects from your function could you put them into a containing array (or better still a Hash so they can be referenced by a given name rather than element number)?

In the calling routine you'll then get an array/hash passed back which contains all the objects passed from the function.

Hope that helps,
Jim
 
Back
Top Bottom