开发者

Does ruby expression expansion via #{} do double expansion?

Okay, per suggestions on clarifying the intent I have restated the question. Hope this example is clear.

$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

So, the idea is to have 开发者_高级运维various debug related strings to use in various places without needing to repeat the same formatting and such.

Anyway, this isn't super critical it's more just an attempt to try and learn Ruby better.

go easy,

-daniel


No, this is not possible as you have shown. the #{} syntax is just for string interpolation, so when you write PP = "[#{fname}]", it's simply storing the string [Empty] in the variable PP. Strings have no memory of what code was used to produce them.

It's unclear what you're attempting to achieve with this, but more than likely a method would be more appropriate than string interpolation.


Update since your edit: It seems you want to create a sort of simulated stack trace. String interpolation still doesn't make sense. Instead, you could do something like this:

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

Based on your strange usage of global variables and constants, it seems you're trying to apply ideas from some other language in ways that don't fit with Ruby. I'd recommend looking through a Ruby book to get familiar with the basics.


You can use eval for this. Just make sure to make "XXX" a very unlikely string to appear in actual message.

$DebugFormat = 'Within #{$funcname} message: #{$message}'

def somefunc
   $funcname = "Something"
   $message = "an important message."
   puts eval("<<XXX\n" + $DebugFormat + "\nXXX\n")
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜