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
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
This question is related to:
before Ruby 2.0, you can use the .to_source
method
Ruby 2.0 and higher
.to_source
has been replaced by .source
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.