11

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
RyanScottLewis
  • 12,386
  • 14
  • 53
  • 83

1 Answers1

10

This question is related to:

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.

Community
  • 1
  • 1
sawa
  • 160,959
  • 41
  • 265
  • 366
  • 8
    In Ruby 2.0 you can print a proc as a string with #source. #to_source no longer works. – mpiccolo Jan 19 '14 at 08:39
  • You need to include the `method_source` gem (and you will need to be in a file, it did not work from irb for me) – Nick B Apr 15 '16 at 18:24