I am a new Ruby recruit (thanks to *ahem*, Rails)..
What is the best way to do this:
* obj.'string'+var as a method?
I am currently using:
* obj.send('string'+var)
...which works fine, but is this correct or bad practice?
I am a new Ruby recruit (thanks to *ahem*, Rails)..
What is the best way to do this:
* obj.'string'+var as a method?
I am currently using:
* obj.send('string'+var)
...which works fine, but is this correct or bad practice?
I'm not sure what's the best way, but here are a few things you could try:
# A hash to play with
h = Hash.new
=> {}
irb(main):112:0> suff = "ore"
=> "ore"
# You can use 'eval' but this is pretty heavy on time and space:
irb(main):113:0> eval("h.st#{suff}('k','v')")
=> "v"
irb(main):114:0> h
=> {"k"=>"v"}
# You can use send, as you did. I'd replace 'str'+var with "str#{var}", but it's not required:
irb(main):115:0> h.send("st#{suff}", 'k', 'g')
=> "g"
irb(main):117:0> h
=> {"k"=>"g"}
# You can get the method and call it as a proc
irb(main):119:0> store = h.method("st#{suff}")
=> #<Method: Hash#store>
irb(main):121:0> store.call('k','g')
=> "g"
irb(main):122:0> store['k','g'] # (shortcut, maybe a bit confusing here though ;))
=> "g"
Hope that helps,
Ross
On Thu, 15 Dec 2005 10:22:47 -0000, bmgz <bmg2x@yahoo.com> wrote:
I am a new Ruby recruit (thanks to *ahem*, Rails)..
What is the best way to do this:* obj.'string'+var as a method?
I am currently using:
* obj.send('string'+var)
..which works fine, but is this correct or bad practice?
--
Ross Bamford - rosco@roscopeco.remove.co.uk
"\e[1;31mL"
bmgz wrote:
I am a new Ruby recruit (thanks to *ahem*, Rails)..
What is the best way to do this:* obj.'string'+var as a method?
I am currently using:
* obj.send('string'+var)
..which works fine, but is this correct or bad practice?
That's ok. As Ross pointed out you can also use obj.send("string#{var}").
But I would not use eval - there's just too much that can go wrong
security wise.
Kind regards
robert