【发布时间】:2013-05-03 17:33:16
【问题描述】:
我正在学习 Ruby,并希望能够做到这一点:
Printer.hi there
并有 Ruby 输出
"hi there"
到目前为止,我有以下实现
class Printer
def method_missing(name, *args)
puts "#{name} #{args.join(',')}"
end
end
但这只能让我做
Printer.hi "there"
如果我尝试
Printer.hi there
我得到一个
NameError: undefined local variable or method `there' for main:Object
这是有道理的,因为我从未定义过“那里”。有没有办法让这项工作?
【问题讨论】:
-
如果有可能并且你做到了,那么它会弄乱整个代码。这样做没有实际意义。
-
不,没有,除非您想办法自动创建未定义的变量。但是,IMO 无论如何都不是一个好的语法,因为它违反直觉。最好创建一个迷你 DSL。
-
虽然我已尽我所能回答,但请注意您的标题不正确。 Ruby 中没有“不带引号的字符串”之类的东西。正如 NameError 所揭示的那样,它们要么是局部变量,要么是方法。
标签: ruby metaprogramming method-missing