打印块的实际Ruby代码?

Rya*_*wis 8 ruby

这可能吗?

def block_to_s(&blk)
  #code to print blocks code here
end

puts block_to_s do
  str = "Hello"
  str.reverse!
  print str
end
Run Code Online (Sandbox Code Playgroud)

这将打印终端的跟随:

str = "Hello"
str.reverse!
print str
Run Code Online (Sandbox Code Playgroud)

saw*_*awa 8

这个问题与以下内容有关:

正如安德鲁在我问这个清单中的第一个时提示我的那样.通过使用gem"sourcify",您可以获得靠近块的东西,但不完全相同:

require 'sourcify'

def block_to_s(&blk)
  blk.to_source(:strip_enclosure => true)
end

puts block_to_s {
  str = "Hello"
  str.reverse!
  print str
}
Run Code Online (Sandbox Code Playgroud)

在上面,请注意您要么必须在puts(block_to_s... end)的参数周围加括号,要么使用{...}而不是do ... end因为stackoverflow中反复讨论的连接强度.

这会给你:

str = "Hello"
str.reverse!
print(str)
Run Code Online (Sandbox Code Playgroud)

这相当于原始块作为ruby脚本,但不是完全相同的字符串.

  • 在Ruby 2.0中,您可以使用#source将proc打印为字符串.#to_source不再有效. (5认同)