Interacting with Ruby’s runtime environment

In this post I will look at various ways of interacting with a Ruby program’s runtime environment. Following sample program has methods to identify the operating system platform, environment variables in the OS and finding out the command line parameters.

CSV processing in Ruby

Ruby is a relatively young language. One of the advantages with this is that Ruby has libraries for common programming needs. In this post, I will show you how easy it is to process CSV files in Ruby.

A CSV file contains comma separated values and is an easy way to store information in text files. In many Web applications, CSV file is generated and is output as excel filetype so that Microsoft excel program can process it.

For this example, let us consider the following CSV file. It contains exam results of 3 students.

Jayson Joseph,39,fail
Thomas Mathew,92,pass
Ravikumar,83,pass

Save this as examresults.txt. Following program shows how this can be read using Ruby. In this example, we will read the exam results, print the name of the people who failed the exam and finally add one more entry to the exam results file. All this can be achieved with minimal plumbing code!

Check out the documentation for complete set of methods available in csv library!

Ruby 1.9.0 development version released

A new development version of Ruby (1.9.0) was released last week. Currently this release is not intended for production use.  There are incompatibilities with 1.8.x series and 1.9.0 is more of a stepping stone for the upcoming 2.0 release.

So what is new in Ruby 1.9.0? Here is a summary,

  • Block arguments are local now. This can break existing code.
  • Introduced a new class called BasicObject.
  • Kernel and Module packages extended.
  • Regular expression engine upgraded.
  • Native threading support.
  • Offers literal hash syntax for parameters. :action = “helloworld” becomes action: “helloworld”.
  • And many more….

It is important to learn these as the next stable version 2.0 will look very much similar to 1.9.0.

Ruby code snippets : RPN Generator

The following program gives good illustration of string functions, regular expressions and blocks. This is a solution to the Reverse Polish Notation generator problem explained at http://www.spoj.pl/problems/ONP/.

Given an algebraic expression with brackets, this program will output the corresponding RPN form. For example, (a+(b+c)) becomes abc++. A good exercise will be to extend this program to use operator precedence in addition to brackets. But that would probably need a better algorithm.

Ruby code snippets : fibonacci series

One of the best ways to start learning Ruby is to try out simple programming problems. Let us see how we can generate fibonacci series using Ruby,

This is a verbose an example. You could achieve the same in a single line!

Starting Ruby development - Day 1 - Install Ruby and Aptana IDE

In the following days I will cover how you can quick start your Ruby learning. Today we will start with Ruby installation and IDE setup.

The first thing you need is a decent IDE so that you can quickly try out Ruby programs. Ruby installation comes with command line tools such as “irb”. But for any real development, a good IDE is necessary. In this example, I will use Aptana IDE which is based on RadRails.

Step 1 : Download and install latest Ruby release.

Step 2: Download and install Aptana IDE.

Step 3: From Aptana IDE, install Ruby extensions (you can exclude rails extensions for faster install). From Aptana, click on Help->Software Updates->Find and Install->Search for new features for install.

Step 4 : Create a Ruby project from Aptana IDE. You can keep all the sample Ruby programs you write here.

Step 5: Write the following sample code in file named ”HelloWorld.rb” and click on “Run HelloWorld.rb”. You should see your first Ruby program output!

Top 5 Ruby projects you must check out

Ruby invasion into the programming world has been swift in the last few months. Obviously one of the reasons was the elegance of the language. But more importantly ruby popularity is driven by tools written on it. It is an open secret that much of the credit goes to Ruby on Rails Web application framework by David Heinemeier Hansson. In this post, I will look at some of the influential tools written on top of Ruby.

rubyonrails.pngRuby on Rails - Arguably the most popular tool written on Ruby. Ruby on Rails is an Agile web application framework which boosts programmer productivity. It uses convention over configuration to cut down on the manual coding. The productivity boost in Rails is due to Ruby elegance and also due to automatic code generation from data model. There are numerous Web apps written on Ruby on Rails - For example, Basecamp and Shopify

typo.gifTypo - Typo is a lean blogging tools powered by Ruby and Ruby on Rails. It is also open source and free. It supports comments, trackbacks/ping, export function and full text search.

logo-big.gifRMagick -  RMagick provides an extension which provides access to ImageMagick and GraphicsMagick image processing libraries from Ruby. Supports a huge set of image formats and comprehensive image processing API.

Instiki - Instiki is a Wiki clone based on Ruby on Rails. It is also possible to use this as a lightweight CMS. David Heinemeier Hansson is one of the project admins. Instiki features all standard wiki features such as file uploads, password protection and feed support. Also provides markup choice between Textile, Markdown and Rdoc.

watir.gifWatir -  Watir is an automatic Web application testing tool written in Ruby. This tool allows you to record user actions and then replay them whenever you want to test the Web app. It also comes with developer toolbar extension for internet explorer.

Rails envy videos on Ruby on Rails

Greg and Jason at railsenvy.com has been running a series of videos comparing Ruby on Rails with other similar technologies.  Here is a collection of them. Some of them are pretty good.

Ruby on Rails and Java

Ruby on Rails and PHP

Ruby on Rails and PHP - 2

Ruby on Rails and PHP - 3

Ruby on Rails and .NET

Ruby on Rails and PHP - 4

Ruby on Rails and Django

Really compact Ruby quick reference guide

Hello World in Ruby

General Rules
Comments start with # and ends with newline
Newlines or semicolon can be used separate expressions
Everything in Ruby is an object. This includes constants such as 5
Since even operators are methods, they can be overridden
Elegant code can be written using blocks feature

Ruby Keywords

alias   and     BEGIN   begin   break   case    class   def     defined
do      else    elsif   END     end     ensure  false   for     if
in      module  next    nil     not     or      redo    rescue  retry
return  self    super   then    true    undef   unless  until   when
while   yield

Ruby Types
Basic types are numbers, strings, ranges, regexen, symbols, arrays, and hashes.

Symbols
:symbol
Unique and comparable values that can be substituted for string keys.

Ranges
1..10 - includes last value (10)
1…10 - excludes last value (10)

Arrays
var = Array.new
var = [10,20]
var = %w (string1,string2)

Hashes
var = Hash.new
var = {1=>2, 2=>3, 3=>4}

Variable Types
$global_variables
@@class_variables
@instance_variables
CONSTANT (caps)
local_variables

Dummy Variables
self - current method’s object
nil
true,false
__FILE__
__LINE__

Predefined Variables

$!         The exception message set by raise call.
$@         Array of backtrace of the last exception thrown.
$&         The string matched by the last successful pattern match.
$`         The string to the left  of the last successful match.
$'         The string to the right of the last successful match.
$+         The last bracket matched by the last successful match.
$1         The Nth group of the last successful match. May be > 1.
$~         The information about the last match.
$=         The flag for case insensitive, nil by default.
$/         The input record separator, newline by default.
$         The output record separator for the print and IO#write.
$,         The output field separator for the print and Array#join.
$;         The default separator for String#split.
$.         The current input line number of the last file that was read.
$<         The virtual concatenation file of the files from command line.
$>         The default output for print, printf. $stdout by default.
$_         The last input line of string by gets or readline.
$0         Contains the name of the script being executed.
$*         Command line arguments given for the script sans args.
$$         The process number of the Ruby running this script.
$?         The status of the last executed child process.
$:         Load path for scripts and binary modules by load or require.
$"         The array contains the module names loaded by require.
$DEBUG     The status of the -d switch.
$FILENAME  Current input file from $<. Same as $<.filename.
$LOAD_PATH The alias to the $:.
$stderr    The current standard error output.
$stdin     The current standard input.
$stdout    The current standard output.
$VERBOSE   The verbose flag, which is set by the -v switch.

Operator Precedence (highest to lowest)
:: .
[]
**
-(unary) +(unary) ! ~
* / %
+ -
<< >>
&
| ^
> >= < <=
<=> == === != =~ !~
&&
||
.. …
=(+=, -=…)
not
and or

Ruby Control Structures

Method Invocation and Definition
method_call
object.method_call
Class::method_call

def method_name
method_body
end

Blocks
method_invocation do … end
method_invocation {

}

Exception Handling (2 forms)

Classes

Accessor Shortcuts
attr_reader
attr_writer
attr

Ruby IDE - Ruby development tools for Eclipse

RDT is an open source IDE for Ruby implemented as an eclipse plugin. So if you are familiar with eclipse platform, this is the best way to start Ruby development. RDT is written in Java along with some Ruby scripts to interface with Ruby code being written.

This tools is far from perfect. It features syntax highlighting, code completion and code formatting. It also provides a basic Test::Unit integration. RDT also comes with a simple regular expression tester.

RDT requires eclipse 3 or above version. You can download Ruby Development Tools here.