<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head profile="http://gmpg.org/xfn/11">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Ruby Tips - My Take on Ruby and Ruby on Rails</title>
	<link rel="canonical" href="http://www.rubytips.org" />
<link rel="stylesheet" href="wp-content/themes/ProSense/style.css" type="text/css" media="screen"/>
<link rel="pingback" href="http://www.rubytips.org/xmlrpc.php"/>
	<link rel="archives" title="December 2011" href="http://www.rubytips.org/2011/12/"/>
	<link rel="archives" title="May 2008" href="http://www.rubytips.org/2008/05/"/>
	<link rel="archives" title="April 2008" href="http://www.rubytips.org/2008/04/"/>
	<link rel="archives" title="January 2008" href="http://www.rubytips.org/2008/01/"/>
	<link rel="archives" title="December 2007" href="http://www.rubytips.org/2007/12/"/>
	<link rel="archives" title="October 2007" href="http://www.rubytips.org/2007/10/"/>
	<link rel="archives" title="September 2007" href="http://www.rubytips.org/2007/09/"/>
	<link rel="archives" title="July 2007" href="http://www.rubytips.org/2007/07/"/>
	<link rel="archives" title="May 2007" href="http://www.rubytips.org/2007/05/"/>
<link rel="dns-prefetch" href="http://s.w.org/"/>
		<script type="text/javascript">
			window._wpemojiSettings = {"baseUrl":"https:\/\/s.w.org\/images\/core\/emoji\/11\/72x72\/","ext":".png","svgUrl":"https:\/\/s.w.org\/images\/core\/emoji\/11\/svg\/","svgExt":".svg","source":{"concatemoji":"http:\/\/www.rubytips.org\/wp-includes\/js\/wp-emoji-release.min.js?ver=4.9.10"}};
			!function(a,b,c){function d(a,b){var c=String.fromCharCode;l.clearRect(0,0,k.width,k.height),l.fillText(c.apply(this,a),0,0);var d=k.toDataURL();l.clearRect(0,0,k.width,k.height),l.fillText(c.apply(this,b),0,0);var e=k.toDataURL();return d===e}function e(a){var b;if(!l||!l.fillText)return!1;switch(l.textBaseline="top",l.font="600 32px Arial",a){case"flag":return!(b=d([55356,56826,55356,56819],[55356,56826,8203,55356,56819]))&&(b=d([55356,57332,56128,56423,56128,56418,56128,56421,56128,56430,56128,56423,56128,56447],[55356,57332,8203,56128,56423,8203,56128,56418,8203,56128,56421,8203,56128,56430,8203,56128,56423,8203,56128,56447]),!b);case"emoji":return b=d([55358,56760,9792,65039],[55358,56760,8203,9792,65039]),!b}return!1}function f(a){var c=b.createElement("script");c.src=a,c.defer=c.type="text/javascript",b.getElementsByTagName("head")[0].appendChild(c)}var g,h,i,j,k=b.createElement("canvas"),l=k.getContext&&k.getContext("2d");for(j=Array("flag","emoji"),c.supports={everything:!0,everythingExceptFlag:!0},i=0;i<j.length;i++)c.supports[j[i]]=e(j[i]),c.supports.everything=c.supports.everything&&c.supports[j[i]],"flag"!==j[i]&&(c.supports.everythingExceptFlag=c.supports.everythingExceptFlag&&c.supports[j[i]]);c.supports.everythingExceptFlag=c.supports.everythingExceptFlag&&!c.supports.flag,c.DOMReady=!1,c.readyCallback=function(){c.DOMReady=!0},c.supports.everything||(h=function(){c.readyCallback()},b.addEventListener?(b.addEventListener("DOMContentLoaded",h,!1),a.addEventListener("load",h,!1)):(a.attachEvent("onload",h),b.attachEvent("onreadystatechange",function(){"complete"===b.readyState&&c.readyCallback()})),g=c.source||{},g.concatemoji?f(g.concatemoji):g.wpemoji&&g.twemoji&&(f(g.twemoji),f(g.wpemoji)))}(window,document,window._wpemojiSettings);
		</script>
		<style type="text/css">
img.wp-smiley,
img.emoji {
	display: inline !important;
	border: none !important;
	box-shadow: none !important;
	height: 1em !important;
	width: 1em !important;
	margin: 0 .07em !important;
	vertical-align: -0.1em !important;
	background: none !important;
	padding: 0 !important;
}
</style>
<link rel="https://api.w.org/" href="http://www.rubytips.org/wp-json/"/>
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://www.rubytips.org/xmlrpc.php?rsd"/>
<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://www.rubytips.org/wp-includes/wlwmanifest.xml"/> 
<meta name="generator" content="WordPress 4.9.10"/>
<style type="text/css" id="syntaxhighlighteranchor"></style>
</head>
<body>
<div id="page">
<div id="header">
			<h1><a href="/">Ruby Tips</a></h1>
			<div class="description">My Take on Ruby and Ruby on Rails</div>
<div class="menu">
<ul>
  <li><a href="/">Home</a></li>
  <li><a href="privacy-policy/">Privacy Policy</a></li>
  <li><a href="about/">About</a></li>
</ul>
</div>	
</div>
<div id="wrapper">
	<div id="content">
			<div class="post" id="post-84">
				<h1><a href="2011/12/22/using-notepad-for-writing-ruby-programs-in-windows/" rel="bookmark" title="Permanent Link to Using Notepad++ for Writing Ruby Programs in Windows">Using Notepad++ for Writing Ruby Programs in Windows</a></h1>
				<div class="entry">
					<p>If you are writing small Ruby programs and you don’t need facilities such as debugging available in a full fledged IDE, I recommend using Notepad++ editor. Notepad++ has built in syntax highlighting for Ruby and is a light weight and fully featured code editor.</p>
<p>Download the latest version of <a href="http://notepad-plus-plus.org/" target="_blank">Notepad++ from here</a>. I recommend download the Windows installer version. The download size is about 5MB. Double click on the downloaded executable to install Notepad++.</p>
<p><img class="entryimage" title="Installing Notepad++ in Windows 7" alt="Installing Notepad++ in Windows 7" src="wp-content/uploads/2011/12/Notepad-v5.9.6.2-Setup-_2011-12-22_00-11-00.jpg"/></p>
<p>Choose the folder where you want Notepad++ to be installed and click on Next.</p>
<p><img class="entryimage" title="Notepad++ installation options" alt="Notepad++ installation options" src="wp-content/uploads/2011/12/Notepad-v5.9.6.2-Setup-_2011-12-22_00-12-24.jpg"/></p>
<p>Customize your installation and choose what you need. I recommend enabling plugins, themes and auto updater. Click on Next.</p>
<p><img class="entryimage" title="Notepad++ installation options" alt="Notepad++ installation options" src="wp-content/uploads/2011/12/Notepad-v5.9.6.2-Setup_2011-12-22_00-13-32.jpg"/></p>
<p>Click on &quot;Don’t use %APPDATA%&quot; option. When you select this option, all the customization you do in your Notepad++ installation will be stored in the installation folder itself. This way you can copy the installed folder to another machine if you need to change your machine.&#160; Click on Install to complete Notepad++ installation.</p>
<p>Run Notepad++ editor by clicking on the desktop icon. Let us first configure Notepad++ for editing Ruby programs.</p>
<p>From the Notepad++ menu, click on Settings =&gt; Preferences. Click on Language Menu/Tab settings. Under the tab settings for [Default] modify the tab size and Replace by space options as shown below. We set the tab size to 2 and we set Replace by space option to use spaces instead of tab character.</p>
<p><img class="entryimage" title="Setting editor properties in Notepad++ for Ruby" alt="Setting editor properties in Notepad++ for Ruby" src="wp-content/uploads/2011/12/Preferences_2011-12-22_00-32-36.jpg"/></p>
<p>Now we will add a custom menu in the Run menu for running Ruby programs. This way you can run Ruby programs directly from the Notepad++ editor. From the Notepad++ menu, click on Run =&gt; Run. This opens up the following window.</p>
<p><img class="entryimage" title="Configuring a shortcut for running Ruby programs in Notepad++" alt="Configuring a shortcut for running Ruby programs in Notepad++" src="wp-content/uploads/2011/12/Run..._2011-12-22_00-18-33.jpg"/></p>
<p>In the text field, enter the following command. In order for this to work, you need to have Ruby 1.9.x installed and the Ruby bin folder must be on the PATH environment variable. <a href="2011/12/20/installing-ruby-on-windows-7-ruby-1-9-x-guide/" target="_blank">See this tutorial for step by step instructions on installing Ruby in Windows</a>.</p>
<blockquote>
<p>cmd /K ruby &quot;$(FULL_CURRENT_PATH)&quot;</p>
</blockquote>
<p>Click on the Save&#8230; button to save this as a custom command.</p>
<p><img class="entryimage" title="Configuring a shortcut for running Ruby programs in Notepad++" alt="Configuring a shortcut for running Ruby programs in Notepad++" src="wp-content/uploads/2011/12/Shortcut_2011-12-22_00-21-07.jpg"/></p>
<p>Enter a name for the shortcut (Run Ruby Program) and then select a keyboard shortcut for running the command (F6). Click on OK.</p>
<p>Now from the Notepad++ menu, Click on Run. You will see the additional &quot;Run Ruby Program&quot; menu as shown below.</p>
<p><img class="entryimage" title="Custom Run Ruby option in Notepad++" alt="Custom Run Ruby option in Notepad++" src="wp-content/uploads/2011/12/image6.png"/></p>
<p>In order for this shortcut to work, you need to ensure that your Ruby program is saved in a file. To test Notepad++, type in the following program,</p>
<pre class="brush: ruby; title: ; notranslate" title="">
def fact(n)
  if n==1
    1
  else
    n * fact(n-1)
  end
end
puts fact(5)
</pre>
<p>Save the file as factorial.rb. Now press F6 key or select the &quot;Run Ruby Program&quot; submenu from the Run menu. You should see the output of the Ruby program in a command window as shown below,</p>
<p><img class="entryimage" title="Ruby program output from Notepad++" alt="Ruby program output from Notepad++" src="wp-content/uploads/2011/12/Administrator-CWindowsSystem32cmd.exe_2011-12-22_00-36-31.jpg"/></p>
				</div>
				<p class="postmetadata"><small>December 22nd, 2011 <!-- by rubyt --> | Posted in <a href="category/ruby-howto/" rel="category tag">Ruby Howto</a> |   <a href="2011/12/22/using-notepad-for-writing-ruby-programs-in-windows/#respond">No Comments</a></small></p>
			</div>
			<div class="post" id="post-69">
				<h1><a href="2011/12/20/installing-ruby-on-windows-7-ruby-1-9-x-guide/" rel="bookmark" title="Permanent Link to Installing Ruby on Windows 7 – Ruby 1.9.x Guide">Installing Ruby on Windows 7 - Ruby 1.9.x Guide</a></h1>
				<div class="entry">
					<p align="left"><img class="entryimage" alt="Ruby Logo" align="right" src="wp-content/uploads/2011/12/image.png"/>This is a step by step guide on installing and using Ruby language on Windows 7 machines. A lot of applications now use the 1.8.x branch of Ruby. However <a href="http://www.ruby-lang.org/en/news/2011/10/06/plans-for-1-8-7/" target="_blank">it is being deprecated</a> and if you are starting Ruby programming, you should start with the 1.9.x branch. This tutorial covers Ruby 1.9.3, the latest production release available as of writing this post.</p>
<p align="left">Ruby 1.9.x introduces a number of key language improvements, faster execution and integrated library/package management using ruby gems. However the migration of tools and packages to Ruby 1.9.x is still on going and getting the language up and running with a decent IDE on Windows requires some effort. A large number of developers including the core Ruby developers use Linux or Mac systems for Ruby development and hence much of the documentation available focuses on installing Ruby on these platforms.</p>
<h2 align="left">Installing Ruby on Windows 7 </h2>
<p align="left">Ruby language is available as open source and ideally you should download the source code and compile it in your development platform to install Ruby. Luckily on Windows, Ruby is available as an installer. Download the latest <a href="http://rubyinstaller.org/downloads/" target="_blank">Windows installer for Ruby from this page</a>.&#160; In this tutorial, I use Ruby 1.9.3-p0 and the download size is around 15MB. Click on the downloaded file to start Ruby installation.</p>
<p align="left"><img class="entryimage" title="Ruby Installation - License Terms" alt="Ruby Installation - License Terms" src="wp-content/uploads/2011/12/Setup-Ruby-1.9.3-p0_2011-12-18_11-18-06.jpg"/></p>
<p align="left">Accept license agreement and click on Next.</p>
<p align="left"><img class="entryimage" title="Ruby Installation - Options" alt="Ruby Installation - Options" src="wp-content/uploads/2011/12/Setup-Ruby-1.9.3-p0_2011-12-18_11-22-10.jpg"/></p>
<p>Enable the &quot;Install Tcl/Tk support&quot; if you are planning to create GUI applications in Ruby. Also select &quot;Add Ruby executables to your path&quot;. This enables you to invoke Ruby interpreter or programs from any command window. Click on Install to complete Ruby installation.</p>
<h2>Exploring Windows Ruby Installation</h2>
<p><img class="entryimage" title="Ruby - What is installed in Windows" border="0" alt="Ruby - What is installed in Windows" align="right" src="wp-content/uploads/2011/12/image1.png"/>Expand the Windows =&gt; Start =&gt; All Programs =&gt; Ruby 1.9.3-p0 to check whether Ruby is successfully installed. You will find the following items in the menu,</p>
<ul>
<li><strong>Interactive Ruby</strong> - This opens a command line Ruby interpreter session. </li>
<li><strong>RubyGems Documentation Server</strong> - The starts an HTTP server by default listening on port 8808. The documentation for all the gems installed in your Ruby installation can be viewed by accessing this URL - http://localhost:8808/ </li>
<li><strong>Start Command prompt with Ruby</strong> - This opens a standard Windows command prompt with ruby’s programs available in the path environment variable. Type in the command <strong>ruby -v</strong> in the command line if you want to verify this. </li>
<li><strong>Uninstall Ruby 1.9.3-p0 - </strong>Get rid of Ruby if you are bored with it </li>
<li><strong>Documentation</strong> - Complete Ruby documentation including the documentation for core and standard library is available as a windows help file. Also included is a free PDF book titled &quot;The Book of Ruby&quot; written by Huw Collingbourne. </li>
</ul>
<h2>Selecting an IDE for Ruby Programming in Windows</h2>
<p>Following are some of the IDEs commonly used in Windows for Ruby programming. </p>
<ul>
<li><a href="http://aptana.com/products/studio3" target="_blank">Aptana Studio</a> </li>
<li><a href="http://netbeans.org/downloads/6.9.1/" target="_blank">NetBeans 6.9.1 or earlier</a> </li>
<li>IntelliJ IDEA with Ruby plugin </li>
<li><a href="http://notepad-plus-plus.org/" target="_blank">Notepad++</a>&#160; (Just an editor, still good for Ruby development) </li>
</ul>
<p>I prefer Aptana Studio 3 for writing Ruby programs in Windows. It has all the cool features you require when you write Ruby programs,</p>
<ul>
<li>It is free! </li>
<li>Supports syntax highlighting </li>
<li>Integrated Ruby debugger! </li>
<li>Code assist and auto completion </li>
<li>Code outline (classes, modules and methods) </li>
</ul>
<h2>Installing Aptana Studio as Ruby IDE in Windows</h2>
<p>Download the standalone Windows installer for <a href="http://aptana.com/products/studio3/download" target="_blank">Aptana Studio 3 from this link</a>. If you already have Eclipse 3.5 or above installed, you can alternatively install just the Aptana plugin to enable Ruby support in Eclipse. However I prefer the standalone version. The download is about 140MB.</p>
<p>Double click on the downloaded installer.</p>
<p><img class="entryimage" title="Installing Aptana Studio 3" alt="Installing Aptana Studio 3" src="wp-content/uploads/2011/12/Aptana-Studio-3-Setup-Select-Installation-Folder_2011-12-18_23-31-28.jpg"/></p>
<p>Select a destination folder for Aptana Studio and click on Next.&#160; Choose defaults for the start menu options in the next screen and click on Next. Select file associations in the screen and click on Next and then click on Install to complete the installation. Installation may take a while since a large number of files are extracted.</p>
<p>Aptana Studio requires a Git version control system installation on your system for its scripting features. Thankfully it can also install a private copy of PortableGit for this purpose. When you start Aptana for the first time, you will be presented with the following screen. </p>
<p><img class="entryimage" title="Aptana Studio 3 - PortableGit Installation" alt="Aptana Studio 3 - PortableGit Installation" src="wp-content/uploads/2011/12/Git-Installation-Not-Found_2011-12-18_23-38-58.jpg"/></p>
<p>Click on &quot;Use PortableGit&quot; button.</p>
<p>Aptana uses the concept of workspaces (from Eclipse) which by default is the location for all the projects you create. You can create the default workspace location from the menu, File =&gt; Workspaces =&gt; Other. If you select another workspace, you will need to configure PortableGit again. Also the workspace folder by default takes over 150MB of hard disk space including PortableGit!</p>
<p>To develop a Ruby program, Click on File =&gt; New =&gt; Ruby Project option from Aptana Studio. Let us create a simple Hello World program. We will create a project and then add our program to this project.</p>
<p><img class="entryimage" title="Creating a new Ruby Project in Aptana Studio 3" alt="Creating a new Ruby Project in Aptana Studio 3" src="wp-content/uploads/2011/12/New-Ruby-Project_2011-12-19_23-06-10.jpg"/></p>
<p>Enter the name of the project as &quot;helloworld&quot; and click on Finish. An empty project will be created in the workspace. From the App explorer or the Project explorer, right click and click on&#160; New =&gt; File.</p>
<p><img class="entryimage" title="Creating a Ruby program in Aptana Studio 3" alt="Creating a Ruby program in Aptana Studio 3" src="wp-content/uploads/2011/12/New-File_2011-12-19_23-08-22.jpg"/></p>
<p>Type in the name of the file as helloworld.rb and click on Finish. Now you have an empty Ruby program in your project. Open helloworld.rb and type in the following program,</p>
<pre class="brush: ruby; title: ; notranslate" title="">
puts &quot;hello world!&quot;
</pre>
<p><img class="entryimage" title="hello world output in Aptana Studio 3" alt="hello world output in Aptana Studio 3" align="right" src="wp-content/uploads/2011/12/image2.png"/>Save helloworld.rb and from Aptana menu, click on Run helloworld.rb. You will see the output of the program in the console window of Aptana. However if you try to debug the program from Aptana, you will get the following error,</p>
<blockquote>
<p>Unable to find &#8216;rdebug-ide’ binary script. May need to install &#8216;ruby-debug-ide’ gem, or may need to add your gem executable directory to your PATH (check location via &#8216;gem environment’).</p>
</blockquote>
<p>In order to debug Ruby programs Aptana requires the ruby-debug-ide gem. Ideally this should be a simple step, but as of writing this blog post, installing it requires a bit of effort.</p>
<h2>Enabling Ruby Debugging Support in Aptana Studio 3</h2>
<p>In order to debug Ruby programs in Aptana, the ruby-debug-ide gem is required. Installing the gem is a simple step. Run the following command from the command line (requires an active internet connection),</p>
<div class="terminal">gem install ruby-debug-ide &#45;&#45;platform=ruby</div>
<p>However this throws up the following error,</p>
<blockquote>
<p>C:\jjc\tools\Ruby193&gt;gem install ruby-debug-ide      <br/>Fetching: ruby-debug-ide-0.4.16.gem (100%)       <br/>ERROR:&#160; Error installing ruby-debug-ide:       <br/>&#160;&#160;&#160;&#160;&#160;&#160;&#160; The &#8216;ruby-debug-ide’ native gem requires installed build tools.</p>
<p>Please update your PATH to include build tools or download the DevKit      <br/>from &#8216;http://rubyinstaller.org/downloads’ and follow the instructions       <br/>at &#8216;http://github.com/oneclick/rubyinstaller/wiki/Development-Kit’</p>
</blockquote>
<p>This means that I need to install Ruby development kit. This kit is required if you want to build native RubyGems from the source code. </p>
<p><a href="http://rubyinstaller.org/downloads/" target="_blank">Download the DevKit compressed file from the Rubyinstaller download page</a>. I downloaded DevKit-tdm-32-4.5.2-20110712-1620-sfx.exe (20MB+ ). This is a 7zip self extracting archive. Run the program and choose a directory where you want DevKit to be installed. I&#160; keep it as a subfolder under the Ruby folder.</p>
<p>Open a windows command prompt and change the directory to the DevKit folder.&#160; Type the following command to configure DevKit installation.</p>
<div class="terminal">ruby dk.rb init</div>
<p>This command will identify the Ruby installed by RubyInstaller as shown below.</p>
<p><img class="entryimage" title="Configuring DevKit for Windows" border="0" alt="Configuring DevKit for Windows" src="wp-content/uploads/2011/12/image3.png"/></p>
<p>Now run the following command to enable DevKit for the Ruby installations in your machine.</p>
<div class="terminal">ruby dk.rb install</div>
<p>For more details on the DevKit installation, <a href="https://github.com/oneclick/rubyinstaller/wiki/Development-Kit" target="_blank">check this page</a>.</p>
<p>Now try installing the ruby-debug-ide gem from the command line. (Note: this step took a couple of minutes in my machine)</p>
<div class="terminal">gem install ruby-debug-ide &#45;&#45;platform=ruby</div>
<p>What I got is another set of errors (see below)! The problem is that the latest release version of ruby-debug-ide (4.16) cannot be built with Ruby 1.9.x. </p>
<blockquote>
<p>Temporarily enhancing PATH to include DevKit&#8230;      <br/>Building native extensions.&#160; This could take a while&#8230;       <br/>ERROR:&#160; Error installing ruby-debug-ide:       <br/>&#160;&#160;&#160;&#160;&#160;&#160;&#160; ERROR: Failed to build gem native extension.</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160; C:/jjc/tools/Ruby193/bin/ruby.exe mkrf_conf.rb      <br/>Building native extensions.&#160; This could take a while&#8230;       <br/>Building native extensions.&#160; This could take a while&#8230;</p>
<p>Gem files will remain installed in C:/jjc/tools/Ruby193/lib/ruby/gems/1.9.1/gems       <br/>/ruby-debug-ide-0.4.16 for inspection.       <br/>Results logged to C:/jjc/tools/Ruby193/lib/ruby/gems/1.9.1/gems/ruby-debug-ide-0       <br/>.4.16/ext/gem_make.out</p>
</blockquote>
<p><img class="entryimage" title="installing ruby-debug-ide" alt="installing ruby-debug-ide" src="wp-content/uploads/2011/12/image4.png"/></p>
<p>This bug is already fixed in the latest source code of ruby-debug-ide. However it is not yet a release version. So we need to tell the gem tool to download and install the latest pre release version by passing the -pre command line switch.</p>
<div class="terminal">gem install ruby-debug-ide &#45;&#45;platform=ruby &#45;&#45;pre</div>
<p>This installs latest pre release version of ruby-debug-ide (version 0.4.17.beta8 as of writing this blog post). </p>
<p><img class="entryimage" title="installing ruby-debug-ide" alt="installing ruby-debug-ide" src="wp-content/uploads/2011/12/image5.png"/></p>
<p>This will enable the debugging feature in Aptana Studio. Check the debugging feature by setting a break point on your program and then clicking on the debug icon. Now you are all set for developing Ruby programs in Windows!</p>
				</div>
				<p class="postmetadata"><small>December 20th, 2011 <!-- by rubyt --> | Posted in <a href="category/ruby-howto/" rel="category tag">Ruby Howto</a> |   <a href="2011/12/20/installing-ruby-on-windows-7-ruby-1-9-x-guide/#comments">7 Comments</a></small></p>
			</div>
			<div id="adsense_homepage_banner">
</div>			
			<div class="post" id="post-43">
				<h1><a href="2008/05/15/distributing-your-ruby-program-as-a-standalone-executable-exe/" rel="bookmark" title="Permanent Link to Distributing your Ruby program as a standalone executable (exe)">Distributing your Ruby program as a standalone executable (exe)</a></h1>
				<div class="entry">
					<p>Since ruby is an interpreted language, whenever you want to release your program you need to release the source code. Also your program users must install Ruby virtual machine before they can run your program. Is there a way to distribute ruby program as a standalone executable?</p>
<p><a title="RubyScript2Exe" href="http://www.erikveen.dds.nl/rubyscript2exe/" target="_blank">Erik Veenstra has created a nifty tool called RubyScript2Exe</a> which can convert your ruby program to an executable program. It achieves this by combining ruby interpreter code and your source code files into a single exe file.</p>
<p>First <a href="http://www.erikveen.dds.nl/rubyscript2exe/#6.0.0" target="_blank">download the RubyScript2Exe tool from here</a>. It is a ruby program (950kb size). Create a simple ruby program called helloworld.rb and save it to the same location where RubyScript2Exe.rb is stored.</p>
<pre class="brush: ruby; title: ; notranslate" title="">
puts &quot;Hello World&quot;
</pre>
<p>From the command prompt, type the following,</p>
<div class="terminal">ruby rubyscript2exe helloworld.rb</div>
<p>You will see the following output on console. Now you have a standalone executable program (helloworld.exe) which can be executed in any Windows machine! Combined with Win32API, you can create cool command line apps for Windows.</p>
<p><img src="wp-content/uploads/2008/05/creating-helloworldexe.jpg" alt="creating windows exe using ruby" class="entryimage"/></p>
<p>The only problem with this executable is that it contains the entire ruby VM and hence is large (helloworld.exe size is around 1.5MB). Also note that this is not really a ruby compiler. It doesn’t convert your ruby code to machine code. It only packages ruby virtual machine along with your ruby code. Hence the code is still interpreted.</p>
<p>RubyScript2Exe can also create executable files for Linux and Mac OS X (Darwin). RubyScrip2Exe is released under GNU GPL license.</p>
				</div>
				<p class="postmetadata"><small>May 15th, 2008 <!-- by rubyt --> | Posted in <a href="category/ruby-tools/" rel="category tag">Ruby Tools</a>, <a href="category/windows-programming/" rel="category tag">Windows Programming</a> |   <a href="2008/05/15/distributing-your-ruby-program-as-a-standalone-executable-exe/#comments">3 Comments</a></small></p>
			</div>
			<div class="post" id="post-39">
				<h1><a href="2008/05/13/accessing-windows-api-from-ruby-using-win32api-library/" rel="bookmark" title="Permanent Link to Accessing Windows API from Ruby – Using Win32API library">Accessing Windows API from Ruby - Using Win32API library</a></h1>
				<div class="entry">
					<p>Ruby is used extensively in Web applications thanks to Ruby on Rails. But you can also develop Windows applications using Ruby. Interestingly the Windows API support is part of the standard installation (only on Microsoft Windows installations) and it is quite easy to use it!</p>
<p>In order to use Windows API, you need to import &#8220;Win32API&#8221; library in your applications.<br/>
You can then use the Win32API class to create a reference to an API method and can call it. The following sample program shows how this can be done. This application will display a native Windows message box,</p>
<pre class="brush: ruby; title: ; notranslate" title=""> 
require &quot;Win32API&quot;
message = &quot;This is a sample Windows message box generated using Win32API&quot;
title = &quot;Win32API from Ruby&quot;
api = Win32API.new('user32', 'MessageBox',['L', 'P', 'P', 'L'],'I')
api.call(0,message,title,0)
</pre>
<p>When you run the above program, you will get a message box similar to the following one,<br/>
<img src="wp-content/uploads/2008/05/win32api-from-ruby.jpg" class="entryimage"/></p>
<p>Now let us analyze our sample program in depth. The first line imports the standard Win32API library. Then we create two variables (message and title) which will hold the message to be displayed and the title of the message box.</p>
<p>Now using Win32API.new, we are creating a new instance of a Windows API method. The first parameter (user32) indicates the DLL which contains the API method. In this case the DLL is user32.dll. The second parameter is the name of the API method (MessageBox). The third parameter is an array indicating the type of all the parameters passed to API method (MessageBox). In the array, L stands for long number and P stands for pointer to string (string variable). The last parameter indicates the return type. In this case I stands for Integer.</p>
<p>Now using call method on the API reference we invoke MessageBox method. Note that the type of parameters matches the third array parameter in the constructor. First parameter is the id of the parent windows (in this case there is no parent and hence 0) and the last parameter indicates the type of message box (0 indicates default message box).</p>
<p>Following is another sample ruby program which uses Windows API to print out the logged in user name and also the computer name,</p>
<pre class="brush: ruby; title: ; notranslate" title="">
require &quot;Win32API&quot;
# Returns the computer name
def getComputerName
  name = &quot; &quot; * 128
  size = &quot;128&quot;
  Win32API.new('kernel32','GetComputerName', ['P','P'],'I').call(name,size)
  return name.unpack(&quot;A*&quot;)
end
# Returns current logged in Windows user name
def getUserName
  name = &quot; &quot; * 128
  size = &quot;128&quot;
  Win32API.new('advapi32','GetUserName', ['P','P'],'I').call(name,size)
  return name.unpack(&quot;A*&quot;)
end
puts &quot;Computer Name: #{getComputerName}&quot;
puts &quot;User Name: #{getUserName}&quot;
</pre>
<p>In the above sample, note that the second parameter is a pointer to the size of the first parameter. In Ruby there are no pointers and hence the size needs to be passed as a string value. Also we need to use unpack method to remove the trailing null character returned by API call.</p>
<p>Check out the following <a href="http://msdn.microsoft.com/en-us/library/ms724432(VS.85).aspx">API definition for GetUserName (from MSDN)</a>,</p>
<pre class="brush: cpp; title: ; notranslate" title="">
BOOL WINAPI GetUserName(
  __out    LPTSTR lpBuffer,
  __inout  LPDWORD lpnSize
);
</pre>
<blockquote><p>
lpBuffer<br/>
A pointer to the buffer to receive the user’s logon name. If this buffer is not large enough to contain the entire user name, the function fails. A buffer size of (UNLEN + 1) characters will hold the maximum length user name including the terminating null character. UNLEN is defined in Lmcons.h.</p>
<p>lpnSize<br/>
On input, this variable specifies the size of the lpBuffer buffer, in TCHARs. On output, the variable receives the number of TCHARs copied to the buffer, including the terminating null character.</p></blockquote>
<p>As you can guess, the parameter passing and parsing return values from API quickly becomes tedious. So from a productivity angle using Windows API to build full fledged Windows applications is not recommended.</p>
				</div>
				<p class="postmetadata"><small>May 13th, 2008 <!-- by rubyt --> | Posted in <a href="category/windows-programming/" rel="category tag">Windows Programming</a> |   <a href="2008/05/13/accessing-windows-api-from-ruby-using-win32api-library/#comments">2 Comments</a></small></p>
			</div>
			<div class="post" id="post-38">
				<h1><a href="2008/05/11/ruby-talk-rb_str_new2-cleanup-ruby-gui-libraries-and-ruby-vs-python/" rel="bookmark" title="Permanent Link to Ruby-Talk – rb_str_new2 cleanup, ruby GUI libraries and Ruby vs Python">Ruby-Talk - rb_str_new2 cleanup, ruby GUI libraries and Ruby vs Python</a></h1>
				<div class="entry">
					<p><em>Note: This is a weekly round up of interesting stuff found on ruby-talk mailing list.</em> <em><a href="http://www.ruby-lang.org/en/community/mailing-lists/" target="_blank">You can subscribe to this list here</a></em>.</p>
<p>1. <a href="http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/67a1c224babb98fb/2a690f9b055b6e96" target="_blank">Steven wondered</a> whether it is necessary to clean up the string created from native C code(rb_str_new2) and passed to rb_funcall. Matz replied,</p>
<blockquote><p>You don’t have to (and you shouldn’t) free string objects.</p></blockquote>
<p>2. <a href="http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/cb01fb982ac99eac/ccad357ccf9f75ca" target="_blank">Mohsin asked which is the better Ruby GUI Library</a>, Ruby-GTK or FXRuby?. Both seemed good candidates and there were some additional recommendations such as JRuby + Swing + Monkeybars(James). Daniel recommended WxRuby,</p>
<blockquote><p>I’ve had very good results with WxRuby http://wxruby.rubyforge.org/; It didn’t take long to learn, is NOT very rubyish (basically the C++ APIs are reimplemented in Ruby), but was very useful for cross-platform development. So you might want to consider that as a third option.</p></blockquote>
<p>3. <a href="http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/1900b19f4db151f6/f9f6e7d6837e2b38" target="_blank">There was a big discussion</a> (started by Marc) on differences between Python and Ruby. Michael had some good points on Ruby,</p>
<blockquote><p>a. Flexible syntax of Ruby</p>
<p>b. Enough support for functional programming without having to fight with the language</p>
<p>c. A friendly community - he laments that this is on the decline!</p>
<p>d. No syntactic whitespace as in Python</p></blockquote>
<p>As Ruby and Rails is becoming a mainstream language/framework it is only natural that you get more of the RTFM type of questions in the mailing groups. In my opinion there is no point in bitching about it, but rather politely point to the relevant documentation.</p>
<p>As far as Rails is concerned it is a big mess. The Rails 2 is out, but there is no documentation for a beginner in Rails 2. All the books are still stuck at earlier versions and for any documentation available online you need to pay! The only book available (3rd edition of Agile Web development with Rails) is still in beta and requires a lot of rewrite before it can be useful. So it is only natural that you get basic rails questions even on Ruby mailing lists and forums!</p>
<p>In another thread <a href="http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/65378457ad782932/524dd4425959d867" target="_blank">Mohit gives this explanation</a>,</p>
<blockquote><p>I see this as a sign that Ruby is picking up and gaining traction in other places.  There was a time when there were a lot of people who were discovering Ruby on their own free will and were looking at documents (online or offline) and trying out different things.  As it gains traction, it approaches the point where people are having Ruby thrust on them (possibly more Rails than Ruby) either due to preference of people further up in the food chain or due to clients (specially in the case of outsourced projects).  In such cases, it’s likely that the engineer is just venting frustration about the language on a forum cos it’s something they werem’t born to, or achieved - it was thrust on them.</p></blockquote>
<p>4. <a href="http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/bc44c03365f17f4d/64e612ae512b513c" target="_blank">Tim wanted to know the best way to delete</a> every other value in a ruby array.  For example [a b c d e f g h i j k] becomes [a c e g i k]. There were a number of solutions proposed,</p>
<blockquote><p>Harry,</p>
<pre class="brush: ruby; title: ; notranslate" title="">
arr = %w[a b c d e f g h i j k]
p arr.select{|x| arr.index(x) % 2 == 0}
</pre>
<p>Yermej,</p>
<pre class="brush: ruby; title: ; notranslate" title=""> a = %w(a b c d e f g h i j k)
1.upto(a.size/2) {|i| a.delete_at i}
</pre>
<p>Joel,</p>
<pre class="brush: ruby; title: ; notranslate" title="">
a = %w(a b c d e f g h i j k)
n = (a.size/2.0).ceil
n.times do |i|
a[i] = a[2*i]
end
a.slice!(n..-1)
</pre>
</blockquote>
				</div>
				<p class="postmetadata"><small>May 11th, 2008 <!-- by rubyt --> | Posted in <a href="category/ruby-talk/" rel="category tag">Ruby Talk</a> |   <a href="2008/05/11/ruby-talk-rb_str_new2-cleanup-ruby-gui-libraries-and-ruby-vs-python/#respond">No Comments</a></small></p>
			</div>
			<div class="post" id="post-37">
				<h1><a href="2008/04/07/10-unique-ruby-language-features/" rel="bookmark" title="Permanent Link to 10 unique ruby language features">10 unique ruby language features</a></h1>
				<div class="entry">
					<p>Learning Ruby is easy if you already know a programming language. But there are some ruby language features which can cause headache for a programmer migrating from C++ or Java. In this post, I will look at 10 interesting language features that are unique to Ruby.</p>
<p><strong>1. Objects everywhere!</strong> - In Ruby everything is an object including simple numeric values. Here is an example,</p>
<pre class="brush: ruby; title: ; notranslate" title="">
  5.times { print &quot;Hello World&quot; }
</pre>
<p><strong>2. Blocks</strong> - Blocks is a powerful feature in Ruby which simplifies programming. Blocks are code blocks which can be passed as a parameter to a method. Using this feature it is easy to build code libraries which can delegate varying functionality to code blocks to be built later. Here is an example which prints out all elements in an array,</p>
<pre class="brush: ruby; title: ; notranslate" title="">
  sample_array.each { |element| print element }
</pre>
<p><strong>3. Implicit return value in methods</strong> - Value of the last expression in a method becomes the return value of the method. In Ruby return keyword is optional. In the following example, 8 is the return value,</p>
<pre class="brush: ruby; title: ; notranslate" title="">
  def testMethod
    x = 4+4
  end
</pre>
<p><strong>4. In Ruby everything is open!</strong> - In Ruby you can easily extend classes and modules. This means that nothing in Ruby (including built in classes and modules) are closed!. Interestingly additional methods can be added to a class even at runtime. Here is an example in which we add a previous method to FixNum class (which is the data type for all integers),</p>
<pre class="brush: ruby; title: ; notranslate" title="">
  class Fixnum
    def previous
      return self-1
    end
  end
  6.previous  # prints 5
</pre>
<p><strong>5. Missing unary operators in Ruby</strong> - Unary operators ++ and &#8212; are not supported in Ruby. Instead you can use += operator.</p>
<p><strong>6. Ruby supports parallel assignment</strong> - It is possible to change multiple variables in a single assignment. The best example is the swapping of two variables as given below,</p>
<pre class="brush: ruby; title: ; notranslate" title="">
  a , b = b, a
</pre>
<p><strong>7. In Ruby strings are mutable - </strong>In Ruby it is possible to change a string variable in place. Hence unlike Java, the same string literal when used multiple times will point to different object instances.</p>
<pre class="brush: ruby; title: ; notranslate" title="">
  print &quot;hello&quot;.object_id
  print &quot;hello&quot;.object_id   # prints a different value
</pre>
<pre class="brush: ruby; title: ; notranslate" title="">
  a = &quot;hello&quot;
  a[1] = &quot;a&quot;
  print a  # prints hallo
</pre>
<p><strong>8. True and false in Ruby</strong> - In Ruby only nil and false evaluate to false. This means that everything else evaluates to true! Hence even the value 0 evaluate to true in ruby. Following code snippet will output &#8220;Hello World&#8221; on console,</p>
<pre class="brush: ruby; title: ; notranslate" title="">
if (0) then
  print &quot;Hello World&quot;
end
</pre>
<p><strong>9. Native support for ranges and regular expressions - </strong>Ruby language has native support for regular expressions and ranges.  This is backed up with a rich set of API methods. Control structures such as a case statement natively supports ranges for value comparison.</p>
<p><strong>10. Method indicators</strong> - In Ruby the last character of a method name can indicate its behaviour. If the method ends with a question mark it indicates that the return value is boolean. If the method ends with an exclamation, it indicates that the method can change the state of the object. In many cases a non exclamation version of the method is provided which modifies a copy of the object.</p>
				</div>
				<p class="postmetadata"><small>April 7th, 2008 <!-- by rubyt --> | Posted in <a href="category/ruby-tips/" rel="category tag">Ruby Tips</a> |   <a href="2008/04/07/10-unique-ruby-language-features/#comments">2 Comments</a></small></p>
			</div>
			<div class="post" id="post-36">
				<h1><a href="2008/01/26/what-is-a-ruby-symbol-symbols-explained/" rel="bookmark" title="Permanent Link to What is a ruby symbol? – symbols explained">What is a ruby symbol? - symbols explained</a></h1>
				<div class="entry">
					<p>Many programmers who are new to Ruby get confused when they see Ruby symbols. A lot us came to know about Ruby language through Ruby on Rails projects. In Ruby on Rails, symbols are everywhere! So it is essential to understand the concept of symbols in Ruby.</p>
<p>A symbol in Ruby is an instance of the class Symbol. A symbol is defined by prefixing a colon with an identifier. <strong>:name</strong>, <strong>:id</strong>, <strong>:user</strong> etc. are examples of symbols.</p>
<p>Let us see what is there in the class Symbol.</p>
<p>Symbol class in Ruby contains one class method all_symbols and instance methods id2name, inspect, to_i, to_int, to_s and to_sym.</p>
<ul>
<li><strong>all_symbols</strong> - Returns an array of all the symbols in Ruby’s symbol table.</li>
<li><strong>id2name</strong> - Returns the string representation of the symbol - :name.id2name returns “name”.</li>
<li><strong>inspect</strong> - Returns the symbol literal</li>
<li><strong>to_i</strong> - Returns an integer unique for each symbol</li>
<li><strong>to_int</strong> - Same as to_i</li>
<li><strong>to_s </strong>- Same as id2name</li>
<li><strong>to_sym</strong> - Convert the symbol to a symbol!</li>
</ul>
<p>Symbols are most commonly used in creating hashes. For example, consider the following hash,</p>
<pre class="brush: ruby; title: ; notranslate" title=""> h = {:name =&gt; &quot;Jayson&quot;, :email =&gt; &quot;admin2@rubytips.org&quot;} </pre>
<p>We could have used strings instead of symbols in this case,</p>
<pre class="brush: ruby; title: ; notranslate" title=""> h = {&quot;name&quot; =&gt; &quot;Jayson&quot;, &quot;email&quot; =&gt; &quot;admin2@rubytips.org&quot;} </pre>
<p>But the advantage in using symbols is the efficient use of memory. Maximum space taken by a symbol is never more than the space taken by an integer. This is because internally symbol is stored as an integer. In case of strings the memory space depends on the size of the string.</p>
<p>Also whenever a string is used in the program, a new instance is created. But for symbols, same identifier points to the same memory location! This can be easily checked by running the following,</p>
<pre class="brush: ruby; title: ; notranslate" title=""> puts &quot;name&quot;.object_id # prints -605705088
puts &quot;name&quot;.object_id # prints -605705108 
puts :name.object_id # prints 34258 
puts :name.object_id # prints 34258 </pre>
<p>The memory saved may look trivial in this case. But when a predefined hash key structure is used as parameter to a method and if the method is used many times in the program, the savings can be substantial! For example, in RoR a sample link is defined as,</p>
<pre class="brush: ruby; title: ; notranslate" title=""> &lt;%= link_to(&quot;Edit&quot;, :controller =&gt; &quot;editcontroller&quot;, :action =&gt; &quot;edit&quot;) %&gt; </pre>
<p>The first parameter is the label used for the link and the second parameter is a hash. The second parameter is defined as a hash to enable dynamic parameters.</p>
<p>Now in the implementation of link_to method, a check is done to see if :action key exists in the hash and then corresponding value is used. Similarly :controller is also checked and if found is used. Hence using hashes is a good way to implement optional parameters.</p>
<p>In this example we could have used “controller” and “action” strings instead of symbols :controller and :action. But we will be missing two important advantages - efficient memory usage and speed of processing.</p>
<p>In a rails application, you might be using link_to hundreds of times. Assume that you have used it 10000 times in a big application. If we assume every call contained :controller and :action symbols, total memory required by the symbols = 2 * size of an integer. Whether we call link_to once or millions of times the memory taken remains same. But things would be different in case of strings as keys. Whenever a link_to is called 2 new strings “controller” and “action” will be created. Hence a total memory allocation of 10000*16 bytes would have done by Ruby interpreter (of course garbage collector will ensure memory usage at any point to be much less than this).</p>
<p>Second is the question of speed. We know that link_to internally compares hash key to :controller and :action. This is extremely fast since it is equivalent to comparing integers. But if we had used strings, comparison such as “controller”==”controller” is inefficient since it involves comparison of all the characters in it.</p>
<p>Strings are scoped and they get destroyed/garbage collected when the execution goes out of scope. But in case of symbols, they remain defined as long as the program is running. So if you have a very large number of symbols there could be a lot of unusable memory.</p>
<p>It is possible convert a string to symbol using the to_sym method. Hence “controller”.to_sym returns :controller. Symbol identifiers can be quoted and they can also contain special characters. Hence <strong>:”wow, this is a symbol!”</strong> is a valid symbol.</p>
<p>In short, symbols are used instead of strings wherever we care only about the identity and not the content. Why we use them? Because they are memory efficient and comparison operation on them are really fast.</p>
<p>Now if you are still confused about symbols, just forget about them. In time you will realize what they are! <img src="wp-includes/images/smilies/icon_smile.gif" alt=":-)" class="wp-smiley"/></p>
				</div>
				<p class="postmetadata"><small>January 26th, 2008 <!-- by rubyt --> | Posted in <a href="category/ruby-tips/" rel="category tag">Ruby Tips</a> |   <a href="2008/01/26/what-is-a-ruby-symbol-symbols-explained/#comments">1 Comment</a></small></p>
			</div>
			<div class="post" id="post-34">
				<h1><a href="2008/01/11/using-temporary-files-in-ruby-tempfilenew/" rel="bookmark" title="Permanent Link to Using temporary files in Ruby – Tempfile.new">Using temporary files in Ruby - Tempfile.new</a></h1>
				<div class="entry">
					<p>For certain programming solutions, you might need a temporary file. Different operating systems store temporary files in different locations. Also you don’t want to explicitly name the file since that is irrelevant in the program. How do you ensure that there are no filename conflicts? The solution for all these is to use library for temp file processing.</p>
<p>Ruby comes a with a default library &#8216;tempfile’ for handling temporary file creation. Given a filename prefix, it creates a temporary file in the following format.</p>
<p>[prefix]-[process].[unique_number]</p>
<p>This ensures that there is no conflict in creating multiple temporary files in the same directory. Once your program terminates the temporary file is automatically deleted. Also by default, the temporary file is created in the operating system’s temporary folder (In my ubuntu system it is /tmp).</p>
<p>In the following program, a temporary file with prefix &#8216;random’ to store 50 random numbers is created. When the program terminates you cannot see the temp file. Hence I have added a &#8216;gets’ which stops for user input. In my case I could see a temporary file named &#8216;random.5789.0’ under \tmp dir.</p>
<pre class="brush: ruby; title: ; notranslate" title="">
require 'tempfile'
class TempSample
temp_file = Tempfile.new('random')
1.upto(50) do
  num = rand(50) # random number generation in ruby
  temp_file.print(num,&quot;\n&quot;) # print number and newline to the file
end
temp_file.flush # flush it so that you can see it using cat
gets # wait for user input. At this point you can see a temp file /tmp
# The filename in my case was random.5789.0
end
</pre>
<p>If you want to the temp file in a specific directory, you can pass the directory name as the second parameter to new. For example - Tempfile.new(&#8216;new1&#8242;,’/usr/home/jay’)</p>
				</div>
				<p class="postmetadata"><small>January 11th, 2008 <!-- by rubyt --> | Posted in <a href="category/code-snippets/" rel="category tag">Code Snippets</a>, <a href="category/ruby-howto/" rel="category tag">Ruby Howto</a> |   <a href="2008/01/11/using-temporary-files-in-ruby-tempfilenew/#comments">3 Comments</a></small></p>
			</div>
			<div class="post" id="post-33">
				<h1><a href="2008/01/10/a-quick-dose-of-ruby-history/" rel="bookmark" title="Permanent Link to A Quick Dose of Ruby History">A Quick Dose of Ruby History</a></h1>
				<div class="entry">
					<p>When you are learning something new, the first thing you should check out is its history. When you go through the history, you get a better perspective. It is the same with Ruby language and hence let us get a quick dose of Ruby history.</p>
<p>Ruby programming language is created by a Japanese programmer, Yukihiro Matsumoto. He is popularly known as &#8220;Matz&#8221; in the Ruby community. Matz started work on the language sometime in February 1993. The first alpha version was released in December 1994. Since then there has been numberous releases and the current production release 1.8.6 was done on March 2007. On 25th December 2007 there was a development release of Ruby 1.9 (this is not intended for production systems).</p>
<p>Ruby 2.0 will be the next major release and it is intended to expand Ruby lanugage and to improve the interpreter performance.</p>
<p>Matz main goal in developing Ruby was to create a scripting language that was more powerful than perl, and more object oriented than Python. Matz named the language after the &#8220;Ruby&#8221; gemstone and is inspired by &#8220;Perl&#8221;. Major guiding philosophy for the language has been &#8220;the principle of least surprise&#8221;. The first thing many new programmers note in Ruby is its elegance.</p>
<p>Following are the key turning points in Ruby history,</p>
<ul>
<li>1993, Feb 24 - Matz starts work on Ruby</li>
<li>1993, April - First &#8220;hello world&#8221; works in Ruby</li>
<li>1995, December 21 - Ruby 0.95 was released to the public</li>
<li>1996, December 25 - Ruby 1.0 was released</li>
<li>1998, December - ruby-talk mailing list was started</li>
<li>2000 - Official Ruby newsgroup started</li>
<li>2001 - RubyConf started</li>
<li>2001, December 15 - Pickaxe book on Ruby was released</li>
<li>2003, August - Ruby 1.8.0 was released</li>
<li>2004, July - Web application framework Ruby on Rails released</li>
<li>2007, March - Ruby 1.8.6 was released</li>
<li>2007, December 25 - Ruby 1.9 (experimental version) was released</li>
<li>??? - Ruby 2.0 release in future</li>
</ul>
				</div>
				<p class="postmetadata"><small>January 10th, 2008 <!-- by rubyt --> | Posted in <a href="category/ruby-history/" rel="category tag">Ruby History</a> |   <a href="2008/01/10/a-quick-dose-of-ruby-history/#respond">No Comments</a></small></p>
			</div>
			<div class="post" id="post-32">
				<h1><a href="2008/01/09/using-rubys-http-library-download-and-process-web-pages-i/" rel="bookmark" title="Permanent Link to Using Ruby’s http library – download and process web pages – I">Using Ruby’s http library - download and process web pages - I</a></h1>
				<div class="entry">
					<p>Ruby has excellent networking support. Ruby has low level networking features such as sockets and tcp/ip protocols. It also has a high level API for handling protocols such as http and ftp. In this post we will look the Ruby http library. We also look at how this library can be used to download and process web pages.</p>
<p><strong>1. Downloading a web page using Ruby</strong></p>
<p>Following code illustrates using net/http library for downloading the Google’s home page. You should see the google homepage html in console!</p>
<pre class="brush: ruby; title: ; notranslate" title="">
require 'net/http'
class HttpSample
def downloadGoogleHome
  http_response = Net::HTTP.get_response( URI.parse('http://www.google.com/'))
  puts http_response.body
end
s = HttpSample.new
s.downloadGoogleHome
end
</pre>
<p>Now in my machine, this returns text which says &#8220;document has moved&#8221;. This is because google is send a redirect to www.google.co.in. Following code shows how we can handle http redirect.</p>
<pre class="brush: ruby; title: ; notranslate" title="">
require 'net/http'
class HttpSample
def downloadGoogleHome
  http_response = Net::HTTP.get_response( URI.parse('http://www.google.com/'))
  if(http_response.kind_of?(Net::HTTPRedirection))
    new_url = http_response['Location']
    http_response = Net::HTTP.get_response(URI.parse(new_url))
  end  
  puts http_response.body
end
s = HttpSample.new
s.downloadGoogleHome
end
</pre>
<p>Now how do we rewrite this if we need to use a proxy server to connect to internet? In Ruby it is pretty simple. Check out the new version below.</p>
<pre class="brush: ruby; title: ; notranslate" title="">
require 'net/http'
class HttpSample
def downloadGoogleHome
  proxy = Net::HTTP::Proxy('ipaddress', portnumber) # use actual ip and port
  url = URI.parse('http://www.google.com')
  http_response = proxy.get_response(url)
  puts http_response.body
end
s = HttpSample.new
s.downloadGoogleHome
end
</pre>
				</div>
				<p class="postmetadata"><small>January 9th, 2008 <!-- by rubyt --> | Posted in <a href="category/code-snippets/" rel="category tag">Code Snippets</a>, <a href="category/ruby-howto/" rel="category tag">Ruby Howto</a>, <a href="category/ruby-tips/" rel="category tag">Ruby Tips</a> |   <a href="2008/01/09/using-rubys-http-library-download-and-process-web-pages-i/#comments">3 Comments</a></small></p>
			</div>
		<div class="navigation">
			<div class="alignleft"><a href="page/2/">&laquo; Previous Entries</a></div>
			<div class="alignright"></div>
			<div style="clear:both;"></div>
		</div>
	</div>
	<div id="sidebar">
			<ul>
<li><p><a href="http://feeds.feedburner.com/RubyTips"><img src="-fc/RubyTips-bg-99CCFF-fg-444444-anim-0.jpg" height="26" width="88" style="border:0" alt=""/></a></p></li>
			<!--
				<li class="pagenav"><h2>Pages</h2><ul><li class="page_item page-item-41 page_item_has_children"><a href="http://www.rubytips.org/free-ruby-book/">Free Ruby Book</a>
<ul class='children'>
	<li class="page_item page-item-42"><a href="http://www.rubytips.org/free-ruby-book/introduction/">Introduction</a></li>
</ul>
</li>
<li class="page_item page-item-45"><a href="http://www.rubytips.org/privacy-policy/">Privacy Policy</a></li>
<li class="page_item page-item-2"><a href="http://www.rubytips.org/about/">About</a></li>
</ul></li>                  -->
<br/>
<li><h2>Recent Articles</h2>
				<ul>
															<li><a href="2011/12/22/using-notepad-for-writing-ruby-programs-in-windows/">Using Notepad++ for Writing Ruby Programs in Windows</a></li>
										<li><a href="2011/12/20/installing-ruby-on-windows-7-ruby-1-9-x-guide/">Installing Ruby on Windows 7 - Ruby 1.9.x Guide</a></li>
										<li><a href="2008/05/15/distributing-your-ruby-program-as-a-standalone-executable-exe/">Distributing your Ruby program as a standalone executable (exe)</a></li>
										<li><a href="2008/05/13/accessing-windows-api-from-ruby-using-win32api-library/">Accessing Windows API from Ruby - Using Win32API library</a></li>
										<li><a href="2008/05/11/ruby-talk-rb_str_new2-cleanup-ruby-gui-libraries-and-ruby-vs-python/">Ruby-Talk - rb_str_new2 cleanup, ruby GUI libraries and Ruby vs Python</a></li>
									</ul>
				</li>
					  <li id="linkcat-2" class="linkcat"><h2>Ruby Links</h2>
	<ul>
<li><a href="http://www.ruby-forum.com/" title="Official Ruby Forum">Ruby Forum</a></li>
<li><a href="http://www.ruby-lang.org/en/" title="Official Ruby Website">Ruby Home</a></li>
<li><a href="http://www.rubyquiz.com/" title="Ruby Programming Problems">Ruby Quiz</a></li>
	</ul>
</li>
				<li><h2>Categories</h2>
					<ul>
						<li class="cat-item cat-item-12"><a href="category/code-snippets/">Code Snippets</a> (7)
</li>
	<li class="cat-item cat-item-14"><a href="category/ruby-history/">Ruby History</a> (1)
</li>
	<li class="cat-item cat-item-13"><a href="category/ruby-howto/">Ruby Howto</a> (6)
</li>
	<li class="cat-item cat-item-7"><a href="category/ruby-news/">Ruby News</a> (3)
</li>
	<li class="cat-item cat-item-11"><a href="category/ruby-on-rails/">Ruby on Rails</a> (1)
</li>
	<li class="cat-item cat-item-10"><a href="category/ruby-reference/">Ruby Reference</a> (1)
</li>
	<li class="cat-item cat-item-15"><a href="category/ruby-talk/">Ruby Talk</a> (1)
</li>
	<li class="cat-item cat-item-6"><a href="category/ruby-tips/">Ruby Tips</a> (7)
</li>
	<li class="cat-item cat-item-9"><a href="category/ruby-tools/">Ruby Tools</a> (4)
</li>
	<li class="cat-item cat-item-3"><a href="category/site-updates/">Site Updates</a> (1)
</li>
	<li class="cat-item cat-item-16"><a href="category/windows-programming/">Windows Programming</a> (2)
</li>
					</ul>
				</li>
                                <li><h2>Other Links</h2>
					<ul>
					<li><a href="https://www.quickprogrammingtips.com/">Programming Tips</a></li>
					<li><a href="http://www.jaysonjc.com/">Jayson Online</a></li>
					</ul>
				</li>
						</ul>
		</div>
		<div style="clear:both;">
	</div></div>
<hr/>
<div id="footer">
		Copyright &copy; <a href="/">Ruby Tips</a>
</div>
</div>
		<script type="text/javascript" src="wp-content/plugins/syntaxhighlighter/syntaxhighlighter2/scripts/shCore_ver-2.1.364.js"></script>
<script type="text/javascript" src="wp-content/plugins/syntaxhighlighter/syntaxhighlighter2/scripts/shBrushRuby_ver-2.1.364.js"></script>
<script type="text/javascript" src="wp-content/plugins/syntaxhighlighter/syntaxhighlighter2/scripts/shBrushCpp_ver-2.1.364.js"></script>
<script type="text/javascript">
	(function(){
		var corecss = document.createElement('link');
		var themecss = document.createElement('link');
		var corecssurl = "http://www.rubytips.org/wp-content/plugins/syntaxhighlighter/syntaxhighlighter2/styles/shCore.css?ver=2.1.364";
		if ( corecss.setAttribute ) {
				corecss.setAttribute( "rel", "stylesheet" );
				corecss.setAttribute( "type", "text/css" );
				corecss.setAttribute( "href", corecssurl );
		} else {
				corecss.rel = "stylesheet";
				corecss.href = corecssurl;
		}
		document.getElementsByTagName("head")[0].insertBefore( corecss, document.getElementById("syntaxhighlighteranchor") );
		var themecssurl = "http://www.rubytips.org/wp-content/plugins/syntaxhighlighter/syntaxhighlighter2/styles/shThemeDefault.css?ver=2.1.364";
		if ( themecss.setAttribute ) {
				themecss.setAttribute( "rel", "stylesheet" );
				themecss.setAttribute( "type", "text/css" );
				themecss.setAttribute( "href", themecssurl );
		} else {
				themecss.rel = "stylesheet";
				themecss.href = themecssurl;
		}
		//document.getElementById("syntaxhighlighteranchor").appendChild(themecss);
		document.getElementsByTagName("head")[0].insertBefore( themecss, document.getElementById("syntaxhighlighteranchor") );
	})();
	SyntaxHighlighter.config.clipboardSwf = 'http://www.rubytips.org/wp-content/plugins/syntaxhighlighter/syntaxhighlighter2/scripts/clipboard.swf';
	SyntaxHighlighter.config.strings.expandSource = 'show source';
	SyntaxHighlighter.config.strings.viewSource = 'view source';
	SyntaxHighlighter.config.strings.copyToClipboard = 'copy to clipboard';
	SyntaxHighlighter.config.strings.copyToClipboardConfirmation = 'The code is in your clipboard now';
	SyntaxHighlighter.config.strings.print = 'print';
	SyntaxHighlighter.config.strings.help = '?';
	SyntaxHighlighter.config.strings.alert = 'SyntaxHighlighter\n\n';
	SyntaxHighlighter.config.strings.noBrush = 'Can\'t find brush for: ';
	SyntaxHighlighter.config.strings.brushNotHtmlScript = 'Brush wasn\'t configured for html-script option: ';
	SyntaxHighlighter.defaults['pad-line-numbers'] = false;
	SyntaxHighlighter.all();
</script>
<script type="text/javascript" src="http://www.rubytips.org/wp-includes/js/wp-embed.min.js?ver=4.9.10"></script>
</body>
</html>