Is it possible to see the ruby code in a proc?
Take a look at the sourcify gem:
proc { x + y }.to_source
# >> "proc { (x + y) }"
How to extract the code from a Proc object?
You can use the ruby2ruby library:
>> # tested with 1.8.7
>> require "parse_tree"
=> true
>> require "ruby2ruby"
=> true
>> require "parse_tree_extensions"
=> true
>> p = Proc.new{test = 0}
>> p.to_ruby
=> "proc { test = 0 }"
You can also turn this string representation of the proc back to ruby and call it:
>> eval(p.to_ruby).call
0
More about ruby2ruby in this video: Hacking with ruby2ruby.
Print the actual Ruby code of a block?
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.
Printing the source code of a Ruby block
You can do this with Ruby2Ruby which implements a to_ruby method.
require 'rubygems'
require 'parse_tree'
require 'parse_tree_extensions'
require 'ruby2ruby'
def meth &block
puts block.to_ruby
end
meth { some code }
will output:
"proc { some(code) }"
I would also check out this awesome talk by Chris Wanstrath of Github http://goruco2008.confreaks.com/03_wanstrath.html He shows some interesting ruby2ruby and parsetree usage examples.
Related Topics
What Grammar Based Parser-Generator Tools Exist for Ruby
Rails: Update Model Attribute Without Invoking Callbacks
Carrierwave Fog Amazon S3 Images Not Displaying
Is There a Ruby Http Client Library with a Response Cache
Run Code Only If Script Called from the Command Line
Run a Ruby Library from the Command-Line
What Are Tainted Objects, and When Should We Untaint Them
Implementing Bayesian Classifier in Ruby
"Gem Update --System Is Disabled on Debian" Error
Is the Unix Philosophy Falling Out of Favor in the Ruby Community
How to Create a Form in Rails Without Having to Use Form_For and a Model Instance
Provide Value for Self When Using Proc#Call
What Rails Plugins Are Good, Stable and *Really* Enhance Your Code