Code Blocks

The Zen of Code Blocks

Code Blocks can be passed to methods:


   def conditional(cond)
     if block_given?
       yield 
     end
   end

   conditional(true) { puts "The condition is true!" } 
   conditional(false) do puts "this will never happen" end

The part between ‘{’ and ‘}’ (or ‘do’ and ‘end’) is the code block. Any code and as much code as you like can go in a code block.

This simple feature is probably one of Ruby’s most powerful. One thing it makes possible is the creation of Domain Specific Languages without the need to create a parser.

QDL (Quantum Design Langauge) example:

Given the quantum circuit:


 0--+-------------
    |
 1--.------.-------
           |
 2--.------+------
    |
 3--.-------------
    |
 4--+-------------

Let’s implement this circuit in QDL:


1   require 'qdl'
2   include QDL
3   circuit = QCircuit.new{
4     io = qBusWidth(5)
5     l0 = qLayer {
6       feynmann(1,0)
7       toffoli(2,3,4)
8     }
9     l1 = qLayer{
10     feynmann(:in=>1,:out=>2)
11   }
12 } #end of circuit


rake (a make replacement)

require 'rake/clean'
CLOBBER.include("*.vhdo")

# Lets make a list of all the .vhd source files in the directory.

VHD_FILES = FileList['*.vhd']

# And now use that to make a list of all the .vhdo file we
# want to generate.

VHDO_FILES = VHD_FILES.sub(/$/, 'o')

task :default => [ :sim_jtag_tb ] do
   puts "done..." 
end

 task :sim_jtag_tb => [ :build_jtag_tb ] do
   puts "simulate it..." 
   sh %{ncsim -gui jtag_tb:jtag_tb_behavior}
end

task :build_jtag_tb => VHDO_FILES do
   puts "build jtag_tb" 
   sh %{ncdlab jtag_tb:jtag_tb_behavior -access +r+w}
end

file "jtag_tb_c.vhdo" => ["jtag_tb_c.vhd"] do
   puts "build jtag_tb_c" 
   sh %{ncvhdl -linedebug jtag_tb_c.vhd}
end

file "jtag_driver.vhdo" => ["jtag_driver.vhd"] do
   puts "build jtag_driver" 
   sh %{ncvhdl -linedebug jtag_driver.vhd}
end

file "jtag.vhdo" => ["jtag.vhd"] do
   puts "build jtag..." 
   sh %{ncvhdl -linedebug jtag.vhd}
end

Back