Computing Magazine

How Ruby Source Code Gets Executed

Posted on the 11 June 2014 by Abhishek Somani @somaniabhi
Programming languages, such as Ruby, are natural and elegant. But to achieve this elegance, things have to happen under the hood. Let's see how does a ruby code is compiled and interpreted. Before moving forward lets see the structure(cross-section) of ruby and its world. How Ruby Source Code Gets Executed 90% of work is done on the surface, so that we focus on developing business value . The following code will be split into tokens by ruby lexer

puts 'Welcome to Ruby World'
Tokenized Representation :

[“puts”,” ”,”'”,”Welcome to Ruby World”,”'”]
Lexed Representation : Lexer Format:

[[line number,column],type,token]

[1,4]:on_sp,” ”]
[1,6]:on_t_string_content,”Welcome to Ruby World”]
Once the code generates token & is lexed , now the parser will start its job by taking the lexed representation and create a Abstract syntax tree.AST:

[:@ident, ”puts” , [1,0] ],
[:string_content],[:@string_content, “Welcome to Ruby World”,[1,6]]]]],
Once AST finishes the job the compiler will convert to byte code, Now it is executed/interpreted by VM This is Implemented in MRI. Ruby uses lex(Lexer) & bison(parser generator). Implementation of Above code in CLI/Ruby Program :

require “ripper”
require “pp”
src= “puts 'Welcome to Ruby World'”
puts “source: #{src}”
puts “tokenized:”
pp Ripper.tokenize(src)
puts “lexed:”
pp Ripper.lex(src)
puts “parsed:”
pp Ripper.sexp(src)
RefNjoy Coding in Ruby !! Thanks to Santosh for writing this post .

Back to Featured Articles on Logo Paperblog