通过#{}进行ruby表达式扩展是否会进行双倍扩展?
问题描述:
好的,根据澄清意图的建议我重申了这个问题。希望这个例子很明显。通过#{}进行ruby表达式扩展是否会进行双倍扩展?
$funcname = ""
$message = ""
$DebugFormat = "Within #{$funcname} message: #{$message}"
def Something
$funcname = "Something"
# .
# .
# .
$message = "an important message."
puts "#{$DebugFormat}"
end
def Another
$funcname = "Another"
# Another method related code ...
$message = "Result message to output"
puts "#{$DebugFormat}"
end
因此,这个想法是有各种调试相关的字符串在各个地方使用,无需重复相同的格式等。
无论如何,这不是超级重要的,它更多的是尝试和更好地学习Ruby。
去容易,
-daniel
答
不,这是不可能的,因为你表现出来了。 #{}
语法仅用于字符串内插,因此当您编写PP = "[#{fname}]"
时,它只是将字符串[Empty]
存储在变量PP
中。字符串不知道用什么代码来生成它们。
目前还不清楚你试图用这个来实现什么,但比字符串插值更适合一种方法。因为你的编辑
更新:似乎要创造一种模拟堆栈跟踪的。字符串插值仍然没有意义。相反,你可以做这样的事情:
def debug(message)
puts "#{ caller[0][/`([^']*)'/, 1]}: #{message}"
end
def something
debug "an important message"
end
def another
debug "result message to output"
end
something
another
根据您的奇怪的全局变量和常量的使用情况,您似乎试图从其他语言中不使用Ruby适合的方式应用的想法。我建议通过Ruby书籍来熟悉基本知识。
答
您可以使用eval。 只要确保将“XXX”作为实际消息中出现的不太可能的字符串。
$DebugFormat = 'Within #{$funcname} message: #{$message}'
def somefunc
$funcname = "Something"
$message = "an important message."
puts eval("<<XXX\n" + $DebugFormat + "\nXXX\n")
end
我必须问 - _why_你想做这个吗?这是一个非常糟糕的设计决策指标。 – 2011-02-18 02:28:17
嗯,我认为这是明确的目的是什么样的例子...我想指定一个全局字符串用于调试输出,并具有方法特定的值反映编写字符串时写入。 – Daniel 2011-02-18 02:31:44