Re: How to create "def method(item)= (value)" ?



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^)

.



Relevant Pages

  • Re: assigning hash to attributes
    ... i'm pretty new to ruby. ... values of this hash to the attributes of that object named like the keys ... assign_params params unless params.nil? ... def assign_params params ...
    (comp.lang.ruby)
  • Rapidshare to Megaupload script
    ... I've made this script and would like to have some input and share it ... def from_rapidshare: ... #returns the authenticated header, in case future changes ... params = urllib.urlencode({'domain': "http://rapidshare.com";, ...
    (comp.lang.python)
  • Re: self in blocks
    ... >> def create ... > but what if i want yield with params, ... # Requires Ruby 1.9 ... technique of defining a method with the proc as the body, ...
    (comp.lang.ruby)
  • Re: How to create "def method(item)= (value)" ?
    ... def initialize ... If you do need to override it, the Hash assignment method is = ... Hash @params, so the only way is by creating an abstraction ...
    (comp.lang.ruby)
  • Re: Python function returns:
    ... Function's params are bindings in the function's local namespace. ... def failsToHaveSideEffects: ... way to return multiple values ...
    (comp.lang.python)