What this line means exactly? (@@active_connections ||= {})


#1

Hi,

I have problem to understand this line does exactly?
this is from the class ConnectionSpecficication,
methode “active_connections”

def self.active_connections #:nodoc:
if allow_concurrency
Thread.current[‘active_connections’] ||= {}
else
@@active_connections ||= {}
end
end

what the line “@@active_connections ||= {}” means
exactly?
as I undertands is if the class varaible
@@active_connections has a value then return the
value, otherwise return {}, but what is {}, a bloc of
nothing??? or what?

Thanks you very much

Saiho


Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com


#2

On 1/24/06, Saiho Y. removed_email_address@domain.invalid wrote:

@@active_connections ||= {}

end
end

what the line “@@active_connections ||= {}” means
exactly?
as I undertands is if the class varaible
@@active_connections has a value then return the
value, otherwise return {}, but what is {}, a bloc of
nothing??? or what?

a = 2
a ||= 3

a is 2

b ||= 3

b is 3

So, ||= will set a variable to some value if the variable doesn’t have
a value yet.

{} is a hash. Could’ve used:
@@active_connections ||= Hash.new
instead.


#3

{} is an anonymous hash

It seems to be saying

“return whatever it is, or initialize it as an empty hash and return
it.”


#4

Yeah, it will use @@active_connections if it has been set, otherwise it
will set @@active_connections to an empty hash and return it.

One thing about this feature has caught me out a couple of times. Look
at this:

x = false
x ||= 4

x = 4 !

x is set to 4 even though it has already been set to false. It does this
because ||= is simply a shortcut for x = x || 4, and (false || 4)
results in 4.

Interesting :slight_smile:

-Jonny.

Kelly Dwight F. wrote:

{} is an anonymous hash

It seems to be saying

“return whatever it is, or initialize it as an empty hash and return
it.”