[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

What's mean? global variables

BlueFox

2/23/2006 3:02:00 PM

in test.rb
class Test
def greeting
"hello world!"
end
end

def test
$test ||= Test.new
end

and somewhere

puts test.greeting

what is mean of(outside of the class define)

def test
$test ||= Test.new
end

and where can find any document?

thanks.


3 Answers

Dave Cantrell

2/24/2006 3:39:00 AM

0

Jacob Fugal wrote:
> $test is a global variable. Thats important in this case for scope --
> $test continues to exist and retain its value between invocations of
> test. The ||= idiom is one commonly found in ruby. It's similar to +=
> in that it is simply short hand for "$test = $test || Test.new". $test
> starts with a value of nil, and the first time test is run (unless you
> manually set $test beforehand), $test is initialized to a new instance
> of Test, since "(nil || anything) == anything". On subsequent runs,
> $test retains its value. From this behavior, ||= can be thought of as
> a "default initializer" operator.

Jacob,

So is this a shortcut for creating a singleton in Ruby? Albeit a
slightly different one I would guess, using a global variable to store a
single instance rather than using a class method to instantiate a new or
return the existing instance.

Thanks...
-dave


BlueFox

2/24/2006 6:47:00 AM

0


> Jacob Fugal wrote:
>> $test is a global variable. Thats important in this case for scope --
>> $test continues to exist and retain its value between invocations of
>> test. The ||= idiom is one commonly found in ruby. It's similar to +=
>> in that it is simply short hand for "$test = $test || Test.new". $test
>> starts with a value of nil, and the first time test is run (unless you
>> manually set $test beforehand), $test is initialized to a new instance
>> of Test, since "(nil || anything) == anything". On subsequent runs,
>> $test retains its value. From this behavior, ||= can be thought of as
>> a "default initializer" operator.
>
> Jacob,
>
> So is this a shortcut for creating a singleton in Ruby? Albeit a slightly
> different one I would guess, using a global variable to store a single
> instance rather than using a class method to instantiate a new or return
> the existing instance.
>
> Thanks...
> -dave
>
>

Oh! the test function just an another way to access the global variable
$test?

yesterday i forgot that we can define a fuction outside classes(unlike
java) and function's return value is the last statement's return value?



Thanks very much.



leo.


Nigel Oldfield

5/9/2010 1:34:00 PM

0

> > I am really looking for a hung one.
>
> > WM
>
> Me too. we got our wish, Nigel

I am wrapped around it, right now ;)

WM