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

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.

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

2008/4/30, Phillip G. [email protected]:

While not the interface you desire, it is the output you want.

Yes, that exactly what I do, but I don’t like it, since it’s not
intuitive. In fact I call the method “set_param(name, value)”. But it
makes the code look like Java… brrrrr… XD

(probably more efficient than the first variant, too.)
Interesting, and thanks for the useful link. :slight_smile:

Hi –

On Wed, 30 Apr 2008, Phillip G. wrote:

| def param(name)= (value)

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’

“#{key.to_sym}” is always going to produce a string, never a symbol.
I’m not sure the OP wants to constrain the keys to be symbols anyway.
Also, you’re calling params; I think you mean param.

So:

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

object.param(my_key, “my_value”)

Also untested, due to laziness :slight_smile:

You could also do:

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

object.param[key] = value

Of course, then one might as well do:

attr_reader :params

on the object, and them:

object.params[key] = value

David

2008/4/30, David A. Black [email protected]:

You could also do:

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

object.param[key] = value

That’s not valid, a method cannot contain []:

irb> def hola end
SyntaxError: compile error
syntax error, unexpected ‘[’, expecting ‘\n’ or ‘;’
def hola end

Of course, then one might as well do:

attr_reader :params

on the object, and them:

object.params[key] = value

Yes, but that is not valid for me since I need to exec some extra code
so I need to create an abstraction layer to access @params.

Thanks.

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

David A. Black wrote:

|> | object.params my_key, ‘my value’
|> => @params[:my_key] => ‘my value’
|
| “#{key.to_sym}” is always going to produce a string, never a symbol.

facepalm Right. String interpolation. Too clever for my own good, is
what I am…

| I’m not sure the OP wants to constrain the keys to be symbols anyway.

Well, given that Rails uses the params hash, with Symbols as keys, I
took a guess. :wink:

Also, it is a bit of a habit on my part to use Symbols, instead of
strings or so.

| Also, you’re calling params; I think you mean param.

Yes, indeed. Typo on my part (I cought it the other two chances…).

|
| 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. :wink:


Phillip G.
Twitter: twitter.com/cynicalryan
Blog: http://justarubyist.blogspot.com

~ “My ethicator machine must’ve had a built-in moral compromise
~ spectral release phantasmatron! I’m a genius!” — Calvin
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkgYb78ACgkQbtAgaoJTgL9uFwCeKmz6hTAVyts6LCR67Va7hvkF
ucQAnR8ZQiObqzUcJD+WbLGRUmnshy5i
=/Utl
-----END PGP SIGNATURE-----

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)

Cheers

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Iñaki Baz C. wrote:

|
| Yes, that exactly what I do, but I don’t like it, since it’s not
| intuitive. In fact I call the method “set_param(name, value)”. But it
| makes the code look like Java… brrrrr… XD

Not commenting on the Java part (the naming in Java is usually rather
well done, IMO), but I agree, the solution isn’t all too elegant because
of it’s lack of intuitive assignment.

Usually, I use something like that, when I am too lazy to create an
optionhash based solution.

adds that to TODO list for a current project

|
| Interesting, and thanks for the useful link. :slight_smile:

You are welcome. :slight_smile:


Phillip G.
Twitter: twitter.com/cynicalryan
Blog: http://justarubyist.blogspot.com

Do you know why the fairy sits at the top of the Xmas tree ?

~ One year, Santa had one tree left over after giving everybody one, and
when one of his fairy helpers asked what she should do with it, he told
her.

~ That`s why.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkgYcJsACgkQbtAgaoJTgL+HaACeMiqRAOW+QZob0dVSghldpG/Z
b7QAoJpDBoN1X8WgA9pxjUwYu1RbJHf3
=DZOH
-----END PGP SIGNATURE-----

2008/4/30, Phillip G. [email protected]:

| 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. :wink:

I’m sorry, but as I’ve replied in this thread that method naming
(using []) is invalid in Ruby :frowning:

2008/4/30, Chris H. [email protected]:

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.

2008/4/30, Phillip G. [email protected]:

Sort of. As a singleton method, you get the syntax error. But not if you
define [] as a method:

irb(main):001:0> def []=(key,value)
irb(main):002:1> end
=> nil

Yes, but I need “def some_name[]” :slight_smile:

Hi –

On Wed, 30 Apr 2008, Iñaki Baz C. wrote:

That’s not valid, a method cannot contain []:
Yikes. Sorry. I’m being stupid. (I think there was some real code of
which that was a wrong version, but now I can’t remember what I
meant…)

David

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Iñaki Baz C. wrote:
| 2008/4/30, Phillip G. [email protected]:
|> | 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. :wink:
|
| I’m sorry, but as I’ve replied in this thread that method naming
| (using []) is invalid in Ruby :frowning:

Sort of. As a singleton method, you get the syntax error. But not if you
define [] as a method:

irb(main):001:0> def []=(key,value)
irb(main):002:1> end
=> nil


Phillip G.
Twitter: twitter.com/cynicalryan
Blog: http://justarubyist.blogspot.com

~ “It’s great to have a friend who appreciates an earnest discussion
of
ideas.” -Calvin
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkgYdR8ACgkQbtAgaoJTgL8u3wCeJBjJgyJ61Uvxx29wpoiYzx+N
YjUAnjvAmG8+itc/5/337GSz37rH64zm
=f5M/
-----END PGP SIGNATURE-----

Hi –

On Wed, 30 Apr 2008, Phillip G. 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. :wink:

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! :slight_smile:

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 :slight_smile:

David

Hi –

On Wed, 30 Apr 2008, Phillip G. wrote:

|> |
irb(main):001:0> def []=(key,value)
irb(main):002:1> end
=> nil

It’s not the singletonness that stops it; you can do this:

def object.[]=(k,v) # etc.

What made my example wrong was that I had concocted an illegal method
name.

David

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

David A. Black wrote:

|>
|> Sort of. As a singleton method, you get the syntax error. But not if you
|> define [] as a method:
|>
|> irb(main):001:0> def []=(key,value)
|> irb(main):002:1> end
|> => nil
|
| It’s not the singletonness that stops it; you can do this:
|
| def object.[]=(k,v) # etc.
|
| What made my example wrong was that I had concocted an illegal method
| name.

Though, it should (might?) be possible to implemetn something like
Hash’s or Array’s

hash[key]
array[index]

index methods for plain old object instances, too.

I haven’t seen such an implementation, though, and my C and Java fu are
too weak to make sense of JRuby or CRuby.

Maybe Rubinius is a starting point, since it supposedly implement core
classes in Ruby.


Phillip G.
Twitter: twitter.com/cynicalryan
Blog: http://justarubyist.blogspot.com

ABORT: Drivel filter is compromised!
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkgYe9kACgkQbtAgaoJTgL+gSwCghRVTOxl1IlMKSoNZzq98d1F1
+88AnRieQmvx+CEX4pidn6qfqJe/5TT7
=3zqI
-----END PGP SIGNATURE-----

Iñaki Baz C. wrote:

#what I want but it’s not possible:

There is always the stupid way

vgs% cat b.rb
#!/usr/bin/ruby
class A
class Int__
def initialize(obj, name)
@self = obj
@name = name
end

  def []=(x, y)
     s = @self
     n = @name
     s.instance_eval {
        instance_variable_get(n)[x] = y
        @modified = true
     }
  end

end

def param
@param ||= {}
Int__.new(self, ‘@param’)
end
end

a = A.new
a.param[:x] = 24
p a
vgs%

vgs% ./b.rb
#<A:0xb7c9e3cc @param={:x=>24}, @modified=true>
vgs%

Guy Decoux

2008/4/30, David A. Black [email protected]:

object[1] = 2

p object.params # { 1 => 2 }

Oh, that seems really interesting, but unfortunatelly I can’t
unerstand at all what yuo do there.
Specially I don’t understand the meaning of first two lines:

object = Object.new
class << object

What does that “class” mean??

Thanks a lot.

Hi –

On Wed, 30 Apr 2008, Iñaki Baz C. wrote:

end
object = Object.new
class << object

What does that “class” mean??

http://www.wobblini.net/singletons.html

David

Hi –

On Wed, 30 Apr 2008, Phillip G. wrote:

|> irb(main):002:1> end
Hash’s or Array’s

hash[key]
array[index]

index methods for plain old object instances, too.

Sure:

def object.
# derive value you want here
end

And then:

object[something]

You always get the [] syntactic sugar for free when you define [].

David

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