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



Hi --

On Wed, 30 Apr 2008, Phillip Gawlowski wrote:

| You could also do:
|
| def param[]=(key,value)
| @params[key] = value
| end
|
| object.param[key] = value

Oh, I'm gonna steal that idiom if you don't mind. ;)

Sorry -- it's wrong. I think I've remembered what I meant to write.
This time, let's go all out and try the code! :-)

object = Object.new
class << object
attr_accessor :params
end
object.params = {}

def object.[]=(key,value)
@params[key] = value
end

object[1] = 2

p object.params # { 1 => 2 }

Too bad -- I kind of liked my garbled rubbish version :-)


David

--
Rails training from David A. Black and Ruby Power and Light:
INTRO TO RAILS June 9-12 Berlin
ADVANCING WITH RAILS June 16-19 Berlin
INTRO TO RAILS June 24-27 London (Skills Matter)
See http://www.rubypal.com for details and updates!

.



Relevant Pages

  • Re: "case when" executes a symbol as method
    ... Thanks David and Devin for pointing that out! ... def good_day ... RAILS ROUTING (new! ... & consulting: Ruby Power and Light, ...
    (comp.lang.ruby)
  • Re: attr_writers within blocks
    ... def initialize ... That won't allow you to set @bar to nil or false, ... David A. Black / Ruby Power and Light, ...
    (comp.lang.ruby)
  • Re: I know this code is not very ruby
    ... Phillip Gawlowski wrote: ... | ~ def method_missing ... Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org ...
    (comp.lang.ruby)
  • Re: attr_writers within blocks
    ... No point defining #bar if you don't want it -- just use attr_writer. ... def bar ... David A. Black / Ruby Power and Light, ...
    (comp.lang.ruby)
  • Re: .each do |foo, bar| what does bar do?
    ... each_key {|key| yield key, self} ... That suffers the same problem as David Black's example. ... def each ... Advancing With Rails, Berlin, Germany, November 19-22 ...
    (comp.lang.ruby)