[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Methods with [] braces can't take block arguments?

vikrambkumar

7/13/2008 8:42:00 PM

Hi All,

I want to create a L2 cache object based on Hash.

Since it's a secondary cache, the object bound to the key may have
expired, but can be recreated.

However I want the get method itself to do get-get-set if the "value"
object has expired. Check the class definition:

#---------
class L2Cache
# use Hash for the store
def initialize
@h = Hash.new
end

# try the hash.. if not found and a block
# to recreate is provided, create the value
# and bind it again
def get(key)
value = @h[key]
if value.nil? && block_given?
puts "value is nil but recreating it using the block" if $DEBUG
value = self[key] = yield
elsif value.nil?
puts "value is nil but not recreate block found" if $DEBUG
end
value
end

# proxy to hash
def [](key)
@h[key]
end

# proxy to hash
def []=(key, value)
@h[key] = value
end
end
#---------

c = L2Cache.new
c[:k] # >> nil
c.get(:k) { "foo"} #>> foo
c[:foo] # >> foo

#----------------

However I cannot make the the default get method using [] take a block
as an argument.

If I define the method as:
#--------
def [](key)
value = @h[key]
if value.nil? && block_given?
puts "value is nil but recreating it using the block"
value = self[key] = yield
elsif value.nil?
puts "value is nil but not recreate block found"
end
value
end
#--------

I can't use c[:k] { block here }

#--------
c = L2Cache.new
c[:k] # >> nil
c.[:k] { "foo"} # >> syntax error, unexpected '{', expecting
$end
#--------

Is there a way to make methods names with special characters take
block arguments?

1 Answer

Jens Wille

7/14/2008 9:07:00 AM

0

hi!

vikrambkumar@gmail.com [2008-07-13 22:40]:
> I can't use c[:k] { block here }
>
> #--------
> c = L2Cache.new
> c[:k] # >> nil
> c.[:k] { "foo"} # >> syntax error, unexpected '{', expecting
> $end
> #--------
>
> Is there a way to make methods names with special characters take
> block arguments?
well, the problem is not that the method name has special
characters, but that what you're using is just syntactic sugar for
that particular method name. it works perfectly fine when you use
the regular syntax:

c.[](:k) { 'foo' } # pretty ugly, eh? ;-)
c.get(:k) { 'foo' }

alternatively, you could pass in a proc argument like this:

c[:k, lambda { 'foo' }]

but you'd have to change your code to take that into account.

cheers
jens

--
Jens Wille, Dipl.-Bibl. (FH)
prometheus - Das verteilte digitale Bildarchiv für Forschung & Lehre
Kunsthistorisches Institut der Universität zu Köln
Albertus-Magnus-Platz, D-50923 Köln
Tel.: +49 (0)221 470-6668, E-Mail: jens.wille@uni-koeln.de
http://www.prometheus-bild...