我正在编写一个带有字符串输入的ruby方法,但我不想输入引号.
例如:
def noquotes(input)
puts input
end
noquotes('12Dec11Bel01') # ---> 12Dec11Bel01
noquotes(12Dec11Bel01) # ---> Currently yields an error
Run Code Online (Sandbox Code Playgroud)
我希望能够做的是输入没有引号的方法输入(第二个例子),仍然得到正确的结果.我尝试使用.to_str来确保输入被视为字符串,但它不起作用.
呵呵,抱歉,但你不能在Ruby中使用语法树.如果您不做引号,它将被解析为变量或方法调用.
你能做的是
def method_missing(meth, *args)
meth.to_s
end
Run Code Online (Sandbox Code Playgroud)
但要明智地使用,并使用范围界定,如
class DSL # You'd use that here
def dsl(&block)
instance_eval(block)
end
def method_missing(meth, *args)
meth.to_s
end
def noquotes(input)
puts input
end
end
def dsl(&block)
DSL.new.dsl(&block)
end
dsl do
noquotes(foobar)
end
Run Code Online (Sandbox Code Playgroud)
只有在您知道自己在做什么的情况下才谨慎使用!而且只在DSL中.甚至没有.真.不要这样做.
| 归档时间: |
|
| 查看次数: |
326 次 |
| 最近记录: |