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

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
@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
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?

hi!

[email protected] [2008-07-13 22:40]:

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. { ‘foo’ } # pretty ugly, eh? :wink:
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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs