Forum: Ruby on Rails what this line means exactly? (@@active_connections ||= {})

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.
14b7344777a56ac9a1fad849f5d6da2a?d=identicon&s=25 sayoyo Sayoyo (sayoyo)
on 2006-01-24 21:35
(Received via mailing list)
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
38a8230ed3d5c685558b4f0aad3fc74b?d=identicon&s=25 Joe Van Dyk (Guest)
on 2006-01-24 21:41
(Received via mailing list)
On 1/24/06, Saiho Yuen <sayoyo@yahoo.com> 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.
6559f9b9607a89074ea5e238d31ffbc2?d=identicon&s=25 Kelly Dwight Felkins (Guest)
on 2006-01-24 21:41
(Received via mailing list)
{} is an anonymous hash

It seems to be saying

"return whatever it is, or initialize it as an empty hash and return
it."
337cdd270761e0e6f4356de45b04d388?d=identicon&s=25 Jonathan Viney (jonny)
on 2006-01-25 01:14
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 :)

-Jonny.

Kelly Dwight Felkins wrote:
> {} is an anonymous hash
>
> It seems to be saying
>
> "return whatever it is, or initialize it as an empty hash and return
> it."
This topic is locked and can not be replied to.