Re: How to create "def method(item)= (value)" ?
- From: Chris Hulan <chris.hulan@xxxxxxxxx>
- Date: Wed, 30 Apr 2008 07:10:39 -0700 (PDT)
On Apr 30, 9:40 am, Iñaki Baz Castillo <i...@xxxxxxxxx> wrote:
2008/4/30, Chris Hulan <chris.hu...@xxxxxxxxx>:
Why not just access param?
class Foo
def initialize
@param = {}
end
attr_accessor :param
end
x = Foo.new
x.param['key'] = 'bar'
If you do need to override it, the Hash assignment method is []=
So I think you can write:
def []=(key,value)
...
Because I need to give value to an attribute of a class containing the
Hash @params, so the only way (AFAIK) is by creating an abstraction
layer and handling the Hash @params via current class methods. This is
my case:
class Uri
# Atributes:
@modified => true/false
@params => Hash
attr_accessor :modified
#what I want but it's not possible:
def param(name)= (value)
@params[name] = value
@modified = true
end
end
I can't do it by extending Hash class since inside Hash class I can't
modify @modified attribute.
Also note there are more ways than "=" to modify a Hash value:
@params[name].strip! , .chomp! , .downcase! ......
and I don't want to redefine all of them so I just want to allow "="
and when it's called @modifed must be true.
Hope I've explained why attr_accessor is not useful for me in this case.
Thanks a lot.
--
Iñaki Baz Castillo
<i...@xxxxxxxxx>
Create your own Hash subclass?
def MyBag
def initialize(parent)
@parent = parent
@theBag = {}
end
def []=(k,v)
@theBag[k] = v
@parent.modified = true
end
def [](k)
@theBag[k]
end
end
class Uri
def initialize
@params = MyBag.new(self) #need to do this in initialize,
otherwise self is not the instance
@modified = false
end
attr_accessor :modified, :params
end
Not tested, and there is most likely a more elegant way to delegate to
Hash, but you get what you pay for 9^)
.
- Follow-Ups:
- Re: How to create "def method(item)= (value)" ?
- From: Iñaki Baz Castillo
- Re: How to create "def method(item)= (value)" ?
- References:
- How to create "def method(item)= (value)" ?
- From: Iñaki Baz Castillo
- Re: How to create "def method(item)= (value)" ?
- From: Phillip Gawlowski
- Re: How to create "def method(item)= (value)" ?
- From: Iñaki Baz Castillo
- Re: How to create "def method(item)= (value)" ?
- From: Chris Hulan
- Re: How to create "def method(item)= (value)" ?
- From: Iñaki Baz Castillo
- How to create "def method(item)= (value)" ?
- Prev by Date: Re: How to create "def method(item)= (value)" ?
- Next by Date: Re: How to create "def method(item)= (value)" ?
- Previous by thread: Re: How to create "def method(item)= (value)" ?
- Next by thread: Re: How to create "def method(item)= (value)" ?
- Index(es):
Relevant Pages
|