12

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
  • 13,396
  • 16
  • 56
  • 84

1 Answers1

11

This question is related to:

  1. before Ruby 2.0, you can use the .to_source method

  2. Ruby 2.0 and higher .to_source has been replaced by .source

  3. 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.

  1. also see the method_source gem github.com/banister/method_source
Jason FB
  • 4,752
  • 3
  • 38
  • 69
sawa
  • 165,429
  • 45
  • 277
  • 381