如何在Ruby变量名中使用字符串?

Tim*_*Tim 4 ruby string variables ruby-on-rails dynamic-variables

我有一个字符串,我想用作变量名称的一部分.具体来说,在Rails路径路径中:

<%= foo_path %>
<%= bar_path %>
Run Code Online (Sandbox Code Playgroud)

我希望路由名称的第一部分是动态的.所以像

@lol = "foo"
<%= [@lol]_path %> # <-- This would really be the "foo_path" variable
Run Code Online (Sandbox Code Playgroud)

Ruby可以这样做吗?

Jor*_*ing 10

当然:

lol = 'foo'

send "#{lol}_path"
# or
send lol + '_path'
Run Code Online (Sandbox Code Playgroud)

说明:Object#send将方法发送到(即"调用"方法)接收器.与任何方法调用一样,没有显式接收器(例如some_object.send 'foo')当前上下文成为接收器,因此调用send :foo等同于self.send :foo.实际上Rails在幕后使用了这种技术(例如).

  • 史诗!!为了教育学的目的,有人会怎么学这样的东西?只是从长期接触Ruby? (3认同)
  • 当然,曝光肯定会有所帮助,但是如果你要使用Ruby,你可能会做更多的事情,而不是尽可能多地阅读文档中的核心类,特别是[对象](http://www.ruby) -doc.org/core-1.9.3/Object.html)和[Kernel](http://www.ruby-doc.org/core-1.9.3/Kernel.html)(但真的[没有] (http://www.ruby-doc.org/core-1.9.3/)很长).不要忘记[Pickaxe](http://www.rubycentral.com/pickaxe/),这是一本开创性(免费)的Ruby书. (2认同)