Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print the actual Ruby code of a block? [duplicate]

Tags:

ruby

Is this possible?

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

puts block_to_s do
  str = "Hello"
  str.reverse!
  print str
end

This would print the follow to the terminal:

str = "Hello"
str.reverse!
print str
like image 677
RyanScottLewis Avatar asked Apr 25 '11 03:04

RyanScottLewis


1 Answers

This question is related to:

  • Converting Proc and Method to String
  • How to extract the code from a Proc object?
  • Ruby block to string instead of executing
  • Compare the Content, Not the Results, of Procs

as Andrew suggested me when I asked the first one in this list. By using the gem 'sourcify', you can get something close to the block, but not exactly the same:

require 'sourcify'

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

puts block_to_s {
  str = "Hello"
  str.reverse!
  print str
}

In above, notice that you either have to put parentheses around the argument of puts (block_to_s ... end) or use {...} instead of do ... end because of the strength of connectivity as discussed repeatedly in stackoverflow.

This will give you:

str = "Hello"
str.reverse!
print(str)

which is equivalent to the original block as a ruby script, but not the exact same string.

like image 199
sawa Avatar answered Nov 15 '22 23:11

sawa