diff --git a/README.md b/README.md index 712cad6..39f696a 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,7 @@ smart people at [Hashrocket](http://hashrocket.com/). - [Are They All True?](ruby/are-they-all-true.md) - [Create an Array of Stringed Numbers](ruby/create-an-array-of-stringed-numbers.md) - [Destructuring Arrays In Blocks](ruby/destructuring-arrays-in-blocks.md) +- [Disassemble Some Codes](ruby/disassemble-some-codes.md) - [Evaluating One-Off Commands](ruby/evaluating-one-off-commands.md) - [Finding The Source of Ruby Methods](ruby/finding-the-source-of-ruby-methods.md) - [Limit Split](ruby/limit-split.md) diff --git a/ruby/disassemble-some-codes.md b/ruby/disassemble-some-codes.md new file mode 100644 index 0000000..d97ffb1 --- /dev/null +++ b/ruby/disassemble-some-codes.md @@ -0,0 +1,31 @@ +# Disassemble Some Codes + +The +[`RubyVM::InstructionSequence`](http://ruby-doc.org/core-2.2.0/RubyVM/InstructionSequence.html) +class makes it easy to compile, disassemble, and inspect bits of Ruby code. +We can quickly take a peek under the hood at a simple ruby statement, such +as `a = 1 + 2`, like so: + +```ruby +> ruby_code = 'a = 1 + 2' +=> a = 1 + 2 +> compiled_code = RubyVM::InstructionSequence.compile(ruby_code) +=> @> +> puts compiled_code.disasm +== disasm: @>========== +local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1, kw: +-1@-1, kwrest: -1]) +[ 2] a +0000 trace 1 ( 1) +0002 putobject_OP_INT2FIX_O_1_C_ +0003 putobject 2 +0005 opt_plus +0007 dup +0008 setlocal_OP__WC__0 2 +0010 leave +=> nil +``` + +It is a bit archaic, but when we get to the line starting with `0002`, we +see values (`1` and then `2`) pushed onto the stack, then operated on, and +finally set on the local variable `a`. Fun!