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:
I am currently using:
…which works fine, but is this correct or bad practice?
On Thu, 15 Dec 2005 10:22:47 -0000, bmgz [email protected] 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?
I’m not sure what’s the best way, but here are a few things you could
try:
h = Hash.new
=> {}
irb(main):112:0> suff = “ore”
=> “ore”
irb(main):113:0> eval(“h.st#{suff}(‘k’,‘v’)”)
=> “v”
irb(main):114:0> h
=> {“k”=>“v”}
but it’s not required:
irb(main):115:0> h.send(“st#{suff}”, ‘k’, ‘g’)
=> “g”
irb(main):117:0> h
=> {“k”=>“g”}
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
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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs