Forum: Ruby treating 'string'+var as method

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
bmgz (Guest)
on 2005-12-15 12:29
(Received via mailing list)
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 B. (Guest)
on 2005-12-15 12:53
(Received via mailing list)
On Thu, 15 Dec 2005 10:22:47 -0000, bmgz <removed_email_address@domain.invalid> 
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:

# 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
Robert K. (Guest)
on 2005-12-15 13:05
(Received via mailing list)
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 topic is locked and can not be replied to.