-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Iñaki Baz C. wrote:
| Hi, is it not possible to create a method to use in this way?
|
| my_object.param(“tag”) = “new_value”
|
| How to define that method? I’ve tryed something as:
|
| def param(name)= (value)
| @params[name] = value
| end
|
| but obviously I get error:
|
| SyntaxError: compile error
| syntax error, unexpected ‘=’
|
| Is there some way? Thanks a lot.
|
Untested, and probably highly inelegant:
def param key, value
~ @params[“#{key.to_sym}”] = value
end
Should produce:
| object.params my_key, ‘my value’
=> @params[:my_key] => ‘my value’
While not the interface you desire, it is the output you want.
(May be useful as a Rails helper, but otherwise?)
Or, you could use an optionhash to create your method:
,http://www.lukeredpath.co.uk/2006/7/27/using-ruby-hashes-as-keyword-arguments-with-easy-defaults>
Something like:
def param(options = {})
~ @params[options.key] = options[options.key]
end
should look like
| object.param ‘key’ => ‘value’
=> @params[‘key’] => ‘value’
You could sexy that up with Hash#merge:
def param(options = {})
~ @params = @params.merge options
end
(probably more efficient than the first variant, too.)
Hope that helps.
Phillip G.
Twitter: twitter.com/cynicalryan
Blog: http://justarubyist.blogspot.com
~ - You know you’ve been hacking too long when…
…you want to wash your hair and think: awk -F"/neck" ‘{ print $1 }’ |
shower
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
iEYEARECAAYFAkgYawQACgkQbtAgaoJTgL82BACgjop7Cr5BFncX8igZrmTsDZJd
rT8Anjx643D6wDFImBbkLWG/rEXA00mv
=r9VE
-----END PGP SIGNATURE-----