A way to do automagical instantiation of variables for a specifictype

C

Charles Comstock

I just discovered a pattern that I have found to be quite useful. In
essence it allows for me to do automagically instantiation of variables
for a specific type. I have found it to be particularly useful in code
that has multiple mutex locks. For instance:

mlock = Hash.new {|h,k| h[k] = Mutex.new }

then later throughout my code when I need mutex I say
mlock["entry"].synchronize do
# blah
end

or
mlock["exit"].synchronize do
# exit blah
end

It's nice because that way I don't have to keep instantiating new
mutexes in the initalization code, I just add one whenever I need it.
Anyway, I thought it was a useful hack and thought I would share it.

Charlie
 
D

daz

Charles said:
I just discovered a pattern that I have found to be quite useful. In
essence it allows for me to do automagically instantiation of variables
for a specific type. I have found it to be particularly useful in code
that has multiple mutex locks. For instance:

mlock = Hash.new {|h,k| h[k] = Mutex.new }

then later throughout my code when I need mutex I say
mlock["entry"].synchronize do
# blah
end

or
mlock["exit"].synchronize do
# exit blah
end

It's nice because that way I don't have to keep instantiating new
mutexes in the initalization code, I just add one whenever I need it.
Anyway, I thought it was a useful hack and thought I would share it.

Charlie


Hope I can find that if I need it.


You might want to upgrade your "keys" from pieces of text to
rock-solid symbols ... mlock[:entry] mlock[:exit] for that
added style edge (?) :)


daz

-----

For another interesting use of the Hash.new block:
### from: www.ruby-talk.org/81135 (Aredridel)

hb3 = Hash.new { |h,k|
Thread.new {
some_task_with_immense_processing_that_assigns_to_h(h, k)
}
"incomplete"
}
 
C

Charles Comstock

I just realized it would be really nice if OpenStruct had a way to set
default values like this as well. I tried stuffing a hash into it that
initalized like this, so that the openstruct would initialize like this
as well, but it didn't work. OpenStruct does not currently take a
block, would a default value for a field in an OpenStruct make sense?

Also related, while it's understandable that OpenStruct tries to avoid
having methods on it as much as possible so they remain open fields, it
might be nice in some circumstances to be able to grab the internal hash
that OpenStruct wraps around.

Charles Comstock
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top