<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>It's not a blog, It's a feature &#187; Ruby</title>
	<atom:link href="http://javazquez.com/juan/category/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://javazquez.com/juan</link>
	<description>Juan A. Vazquez</description>
	<lastBuildDate>Wed, 16 Nov 2011 02:45:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Ruby&#8217;s variable variables</title>
		<link>http://javazquez.com/juan/2009/08/31/rubys-variable-variables/</link>
		<comments>http://javazquez.com/juan/2009/08/31/rubys-variable-variables/#comments</comments>
		<pubDate>Tue, 01 Sep 2009 02:13:15 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[scope]]></category>
		<category><![CDATA[variable]]></category>

		<guid isPermaLink="false">http://javazquez.com/juan/?p=229</guid>
		<description><![CDATA[Hello everyone, This is a quick post that should help developers new to Ruby. It may also help out those that have been away from the language for a while. Its just a quick reference to Ruby&#8217;s variables and their respective scopes. I know I had a chart to keep it all straight when I [...]]]></description>
			<content:encoded><![CDATA[<p>Hello everyone,</p>
<p>This is a quick post that should help developers new to Ruby. It may also help out those that have been away from the language for a while. Its just a quick reference to Ruby&#8217;s variables and their respective scopes. I know I had a chart to keep it all straight when I first encountered the language.</p>
<ol>
<li>@ 	 An instance variable</li>
<li>[a-z] or _ 	A local variable</li>
<li>[A-Z] 	A constant</li>
<li>@@	A class variable</li>
<li>$ 	A global variable</li>
</ol>
<p>This information is easily found on the net if you know what you are looking for. I just posted it to help make it even easier to find for those that are new to Ruby, or new to code writing <img src='http://javazquez.com/juan/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  .</p>
]]></content:encoded>
			<wfw:commentRss>http://javazquez.com/juan/2009/08/31/rubys-variable-variables/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mergesort and Quicksort with Dynamic Languages</title>
		<link>http://javazquez.com/juan/2009/01/03/mergesort-and-quicksort-with-dynamic-languages/</link>
		<comments>http://javazquez.com/juan/2009/01/03/mergesort-and-quicksort-with-dynamic-languages/#comments</comments>
		<pubDate>Sat, 03 Jan 2009 18:10:58 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[Erlang]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[mergesort]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[quicksort]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[sorting]]></category>

		<guid isPermaLink="false">http://javazquez.com/juan/?p=64</guid>
		<description><![CDATA[Groovy, Ruby, Python, Erlang Mergesort, and Quicksort code examples]]></description>
			<content:encoded><![CDATA[<p>The other day I was flipping through an algorithms book and came across a section on sorting. I remembered that I had a blast writing them c++ during my undergrad and thought it would be fun to write them in a couple of different languages. I settled on writing a quicksort, and mergesort.<br />
  <strong>Interesting notes:</strong><br />
<strong>1)</strong> Python(2.5) returns a None type when appending a value to an empty list which forced me to use &#8216;+&#8217;<br />
 >>> ex= [].append()<br />
 >>> print ex<br />
 >>>None</p>
<p><strong>2)</strong> Groovy gave me a <strong>java.util.ConcurrentModificationException</strong> when I transcribed my Ruby code to Groovy. Because of the fact that I was deleting items from a list that I would read in later(while loop which checks size of left and right), I got this error. Accounting for that, the groovy code is pretty nasty.(anyone that would like to provide a better example without relying on the built in Collections.sort(list) would be welcome)</p>
<p> Here is my code&#8230; enjoy!</p>
<pre><code>
# javazquez.com
==========MERGE SORT========

-------------RUBY----------------

def merge_sort(ary)
  return ary if (ary.length <= 1)
  half = ary.length/2
  left = merge_sort(ary[0...half])
  right = merge_sort(ary[half..ary.length-1])
  result =[]
#compare first left and first right
  while left.length > 0 and right.length > 0
    result << (left[0] < right[0] ? left.shift : right.shift)
  end
  result.concat((left.length > 0 ? left : right))
  return result
end

ary=[1,5,14,3,2,45,2,0,01,-1]
p merge_sort(ary)
</code>
<code>
-----------Python Mergesort-------------

def merg_sort(lst):
    if(len(lst) <= 1):  return lst
    left = merg_sort(lst[:len(lst)/2])
    right = merg_sort(lst[len(lst)/2:len(lst)])
    result = []
    while len(left) > 0 and len(right)> 0:
        if( left[0] > right[0]):
            result.append(right.pop(0))
        else:
            result.append(left.pop(0))

    if(len(left)>0): result.extend(merg_sort(left))
    else: result.extend(merg_sort(right))

    return result

print merg_sort([8,7,43,2,5])
</code>
<code>
--------Erlang Mergesort-------------
-module(mergesort).
-export([ms/1,msTestSuite/1]).

ms(Lst)->break(Lst).
break([]) -> [];
break([L]) -> [L];
break(List) ->
    {Left, Right} = lists:split(length(List) div 2, List),
    merge(break(Left),break(Right)).

merge(L, []) -> L;
merge([], R) -> R;
merge([Lh|Ltail],[Rh|Rtail])->
	 if
	 Lh < Rh -> [Lh | merge(Ltail,[Rh|Rtail])];
	 Lh >= Rh -> [Rh | merge(Rtail,[Lh|Ltail])]
	 end.

%to test, run mergesort:msTestSuite(run).
msTestSuite(run)->
	[mstest1(run),mstest2(run),
	mstest3(run),mstest4(run),
    mstest5(run)].

mstest1(run)-> ms([3,2,1]).
mstest2(run)-> ms([3,3,3,1]).
mstest3(run)-> ms([]).
mstest4(run)-> ms([1]).
mstest5(run)-> ms([123,0,-1,23,2,34,5,678,7,5,8]).
</code>
<code>
-------------GROOVY MERGESORT--------
def ms(lst){
    if(lst.size() <= 1){return lst}
    def sz=lst.size()
    int half = (int)(sz/2)
    def l = lst [ 0 .. < half]
    def r = lst [ half.. < sz]
    def lft = ms(l)
    def rht  = ms(r)
    def result = []
    def rcnt = 0
    def lcnt = 0
   while( lcnt < lft.size() &#038;&#038; rcnt < rht.size()){
        if(lft[lcnt] < rht[rcnt]){
        	result += lft[lcnt++]
		}
        else{
			result += rht[rcnt++]
		}
     }
    if(lcnt < lft.size()){
		result +=  ms(lft[lcnt..< lft.size()])
	}
    else{
		result += ms(rht[rcnt..< rht.size()])
	}
    return result
}

sl=[3,88,5,3,2,1,-2,2]
println ms(sl)
</code>

<code markup="none">
# javazquez.com
========QUICKSORT========

-----RUBY----------------
def quick_sort(ary)
  return ary if(ary.length <= 1)
  greater,less = [],[]
  pos = rand(ary.length)
  pivot = ary[pos]
  ary.delete_at(pos)
  ary.each{|item|
       (item < pivot) ? less << item :greater << item}
  return (quick_sort(less) << pivot).concat(quick_sort(greater))
end

ary=[1,5,14,3,2,45,2,0,01,-1]
p quick_sort(ary)
</code>
<code>
----------Python Quicksort--------------

import random
def quickSort(lst):
	if(len(lst) <= 1):return lst
	greater = []
	less = []
	pivot = lst.pop(random.randint(0,len(lst)-1))
	for item in lst:
		if(item < pivot): less.append(item)
		else: greater.append(item)
	return quickSort(less)+[pivot]+quickSort(greater)

ary=[1,5,14,3,2,45,2,0,01,-1]
</code>
<code>
----------Erlang Quicksort--------------
-module(quicksort).
-export([qsort/1]).

qsort([]) ->[];
qsort([Pivot|T]) ->
		lists:append( [qsort([X || X <- T, X < Pivot]),
		[Pivot], qsort([X || X <- T, X >= Pivot]) ).

-------GROOVY QUICKSORT--------------
def quickSort(lst){
	if(lst.size() <= 1){return lst}
	def greater = []
	def less = []
	def pivot = lst.remove(new  Random().nextInt(lst.size()))
	lst.each{item->
		if(item < pivot){ less.add(item)}
		else{greater.add(item)}
	}
	return quickSort(less)+[pivot]+quickSort(greater)
}
print quickSort([1,5,14,3,2,45,2,0,01,-1])

</code>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://javazquez.com/juan/2009/01/03/mergesort-and-quicksort-with-dynamic-languages/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Ruby to Python Primer</title>
		<link>http://javazquez.com/juan/2008/12/16/ruby-to-python-primer/</link>
		<comments>http://javazquez.com/juan/2008/12/16/ruby-to-python-primer/#comments</comments>
		<pubDate>Tue, 16 Dec 2008 16:44:15 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Ruby Questions]]></category>

		<guid isPermaLink="false">http://javazquez.com/juan/?p=35</guid>
		<description><![CDATA[Here is a quick list of similarities between the two languages.
#ruby
puts s.methods 

#python
print dir(s)
]]></description>
			<content:encoded><![CDATA[<p>If your like me, you bounce around between languages a lot. Lately, I have been writing python code. It&#8217;s not Ruby <img src='http://javazquez.com/juan/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  , but it can get the job done. Here is a quick list of similarities between the two languages. I hope it helps&#8230; don&#8217;t forget to this list in the comments section <img src='http://javazquez.com/juan/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /><br />
<code><br />
#-----find object methods-----<br />
s="hello, I am a string"</p>
<p>#ruby<br />
puts s.methods </p>
<p>#python<br />
print dir(s)</p>
<p>#find out more about a method using python<br />
help(s.split)</p>
<p>#-----view object's class-----<br />
#ruby<br />
s.class </p>
<p>#python<br />
s.__class__</p>
<p>#------Iterate hashes-------</p>
<p>#ruby<br />
h.each{|key,value| puts "#{key}, #{value}"} </p>
<p>#python<br />
for key,value in h.iteritems():<br />
  print key, value</p>
<p>#---ternary operators</p>
<p>#ruby<br />
condition ? var = x : var = y</p>
<p>#python.. not exactly an operator, but you get the meaning<br />
#---- var = y  if condition is false<br />
var = x if condition else y     </p>
<p>#----lengths------<br />
#ruby<br />
s="hello, I am a string"<br />
puts "Length of string is #{s.length} or #{s.size}" </p>
<p>h={:one=>2,:three=>4}<br />
puts "Length of hash is same as string, #{h.length} or #{h.size} "</p>
<p>#python<br />
print("This is the length of a string %s" % len("string"))<br />
print("number of key/value pair= %d" % len({'one':1,'two':2}))</p>
<p>#---slicing lists/arrays<br />
l=[1,2,3,4,5]</p>
<p>#ruby<br />
l[1..3] #=>[2,3]</p>
<p>#python<br />
l[1:3] #=>[2,3]</p>
<p>#--print string multiple times-----</p>
<p>#ruby<br />
4.times{print "hello"} #=> hellohellohellohello</p>
<p>#python<br />
print("hello" * 4) #=> hellohellohellohello</p>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://javazquez.com/juan/2008/12/16/ruby-to-python-primer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby HTTPS POST&#8217;ing</title>
		<link>http://javazquez.com/juan/2008/12/07/ruby-https-posting/</link>
		<comments>http://javazquez.com/juan/2008/12/07/ruby-https-posting/#comments</comments>
		<pubDate>Mon, 08 Dec 2008 05:21:58 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Howto]]></category>
		<category><![CDATA[HTTPS]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://javazquez.com/juan/?p=15</guid>
		<description><![CDATA[Code that POST's to HTTPS with ruby]]></description>
			<content:encoded><![CDATA[<p>So for my own geeky pleasure, I decided to try writing cgi scripts with Ruby, Python, PHP, and Perl.  All had readily accessible documentation on how to POST to a https URL but ruby. My first thought was to look at the Net:HTTP documentation found <a href="http://www.ruby-doc.org/stdlib/libdoc/net/http/rdoc/index.html">HERE.</a></p>
<p>The one example I wanted was not listed. I did some searching around and pieced together the following code. I hope this is as big a help to you as it was to me. Looking at it, It seems pretty intuitive&#8230;.but if your like me, sometimes you need it spelled out <img src='http://javazquez.com/juan/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />   </p>
<p><strong>As a side note, setting path to path = &#8216;/../&#8217; is my work-around for a script that is mapped to www.mysite.com</strong> rather than &#8216;/some_POST_handling_script.rb&#8217;</p>
<p><code><br />
#Juan Vazquez ->javazquez.com<br />
require 'net/http'<br />
require 'net/https'<br />
http = Net::HTTP.new('www.mysite.com', 443)<br />
http.use_ssl = true<br />
#path(a.k.a) ->www.mysite.com/some_POST_handling_script.rb'<br />
path = '/some_POST_handling_script.rb'<br />
data = 'badguy=Gargamel'</p>
<p>headers = {'Content-Type'=&gt; 'application/x-www-form-urlencoded'}</p>
<p>resp, data = http.post(path, data, headers)</p>
<p>puts 'Code = ' + resp.code<br />
puts 'Message = ' + resp.message<br />
resp.each {|key, val| puts key + ' = ' + val}<br />
puts data</p>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://javazquez.com/juan/2008/12/07/ruby-https-posting/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Recursive Directory Search with Ruby and Groovy</title>
		<link>http://javazquez.com/juan/2008/11/06/recursive-directory-search-with-ruby-and-groovy/</link>
		<comments>http://javazquez.com/juan/2008/11/06/recursive-directory-search-with-ruby-and-groovy/#comments</comments>
		<pubDate>Thu, 06 Nov 2008 23:58:45 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://javazquez.com/juan/?p=14</guid>
		<description><![CDATA[Recursive file directory search written in both Ruby and Groovy.]]></description>
			<content:encoded><![CDATA[<p>A while back I was bored and decided I need to brush up on my Ruby chops. I had been wanting to play with threads for quite some time and couldn&#8217;t think of anything that would be a fun project to do&#8230;until this crazy idea hit me.  <em>&#8220;</em><em>W</em><em>ouldn&#8217;t it be cool if could generate multiple threads to search different servers for any file of my choosing?&#8221;</em> The code I wrote doesn&#8217;t directly do this, but with some minor tweaks it could be done.</p>
<p><em> </em>I took that idea and ran with it using Ruby. After I finished coding, I thought I would try writing it from scratch using my second favorite language, Groovy (Ruby is my first).  I have to admit, writing the Groovy code was more intuitive because of the baked in file/directory iterators. I refactored my Ruby code a few times and ended up using the find module to maximize performance. Below is the code, and as always, I am open to suggestions on other ways of doing it <img src='http://javazquez.com/juan/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p><strong>Ruby code</strong><br />
 <br />
<code>
<pre>
#########################
#  Juan Vazquez
#  http://javazquez.com
#########################
require 'find'
class DirectoryWizard
  attr_accessor :root_dir,:exts, :thread_cnt, :thread_tracker, :count
  #initialize with a root , and file extensions
  def initialize(root, t_count,*extensions)
    @root_dir, @exts, @thread_cnt , @thread_tracker, @count = root, extensions, t_count, [], 0
  end

  def start_looking
    begin
      puts Dir.entries(@root_dir).select{|dir_item| is_in_ext(dir_item) }
      list_dirs(@root_dir).each do|di|
        @thread_tracker << Thread.new(@root_dir+di){|directory|
                                             recursive_file_search(directory) }
        wait_for_running_threads  if(@thread_tracker.size > @thread_cnt)
      end
      wait_for_running_threads
    rescue Exception => e; puts e;
    end
  end
  def recursive_file_search(directory)
    Find.find(directory){|dir_item|
      if(is_in_ext(dir_item))
       @count+=1
       puts dir_item
      end
    }
  end

    #return array of immediate subdirectories excluding . and ..
  def list_dirs(directory)
   Dir.entries(directory).select{|fh|(!is_p_c_directory?(fh) &#038;&#038;
                                          File.directory?(directory+fh))}
  end

  #return an array of all file/directories excluding '.' and '..'
  def list_contents(directory)
    Dir.entries(directory).delete_if{|x| is_p_c_directory?(x)}
  end

  #is Parent or Current Directory
  def is_p_c_directory?(filename);(filename =="." || filename == "..");end

#return an array of files that match ext
  def is_in_ext(dir_item); @exts.detect{|ext| dir_item.match(ext)}; end

 def wait_for_running_threads
    @thread_tracker.each{|th|th.join}
    @thread_tracker=[]
  end
end #end class

t= DirectoryWizard.new("\\\\server\\e$\\profiles\\",16,'filename')

t.start_looking

puts "Done with Program count is #{t.count}"
</pre>
<p></code></p></blockquote>
<p><strong>Groovy Code</strong></p>
<p><code>
<pre>
import java.util.regex.*;
class DirWiz{
   def root_dir, exts, thread_max_cnt, thread_tracker, count

   public DirWiz(String basedir, int t_count, List extensions){
        this.root_dir = basedir
        this.exts = compile_regex(extensions)
        this.thread_max_cnt = t_count
        this.thread_tracker = []
        this.count=0
    }
    def start_looking(){
      try{
          def dir = new File(this.root_dir)
           check_for_files(this.root_dir)
          //recursively search directories
           dir.eachDir{ subDir->
            //thread it off
           if(this.thread_tracker.size() > this.thread_max_cnt){
               this.thread_tracker.each{it->it.join()}
               this.thread_tracker=[]
           }
           this.thread_tracker << Thread.start{
                 subDir.eachFileRecurse{ fh ->
                    check_using_compiled_regex(fh.canonicalPath)
                 }
           }
        }
      }catch(Exception e){
        println("error ${e}")
      }
      this.thread_tracker.each{it->it.join()}
      println("Done")
    }
   def print_if_match(String file){this.exts.each{ext->
                if(file=~ext){this.count+=1;println(file)}}
   }
   def check_using_compiled_regex(String file){
    try{
	def var = this.exts.find{it.matcher(file).matches()}
	if(var){this.count+=1;println(file)}
    }catch(Exception e){println("Not a Directory ${dir}\n$e")}
   }
   def check_for_files(String dir){
      try{ new File(dir).eachFile{ file ->
	        check_using_compiled_regex(file.canonicalPath)
        }
      }catch(Exception e){println("Not a Directory ${dir}\n$e")}
   }
   def compile_regex(List list){
    List ret_list=[]
    list.each{ ret_list <<    Pattern.compile(it,Pattern.CASE_INSENSITIVE)}
    return ret_list
   }
}

def t = new DirWiz('c:\\',16,[".*\\.jpg.*"])//look for jpegs
//def t = new DirWiz('\\\\server\\dir\\',16,["filname"])
t.start_looking()

println("Done with the program total number of files is ${t.count}")
</pre>
<p></code><br />
 </p>
<p> </p>
]]></content:encoded>
			<wfw:commentRss>http://javazquez.com/juan/2008/11/06/recursive-directory-search-with-ruby-and-groovy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>File I/O Part 1</title>
		<link>http://javazquez.com/juan/2008/06/27/file-io-part-1/</link>
		<comments>http://javazquez.com/juan/2008/06/27/file-io-part-1/#comments</comments>
		<pubDate>Fri, 27 Jun 2008 22:30:44 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://javazquez.com/juan/?p=9</guid>
		<description><![CDATA[I love to learn and try new languages. Not only is learning a new language fun, many times it teaches me something new about a language that I am already familiar with. The only problem that I have with learning so many languages, is keeping them straight. I decided that I would take a few [...]]]></description>
			<content:encoded><![CDATA[<p>I love to learn and try new languages. Not only is learning a new language fun, many times it teaches me something new about a language that I am already familiar with. The only problem that I have with learning so many languages, is keeping them straight. I decided that I would take a few of the dynamic languages I use most often and compile a list of how to handle File I/O with each of them. If you have a Dynamic language(part 2 of this post will be on static languages) not represented below or have another method of File I/O with the represented languages, please add to the list with its respective File I/O code:D<br />
Without further ado&#8230;</p>
<blockquote>
<pre>//Groovy open file for writing
def target ="filename"
File wf= new File(target)
wf.write( "I am in your file eating your space" )

//Groovy open file for appending
def target ="filename"
File af= new File(target)
af.append("I have all of your base")

//Groovy read each line in file
new File("filename").eachLine{line-&gt; println line}

//Groovy read whole document and put into List

List lines = new File("filename").readLines()
//lines contains two lines that we need
println "first line  $lines[0]"
println "second line $lines[1]"

//Groovy reading one line
File rf= new File("filename") //open for reading
//read first line, trim, assign to tmp
rf.withReader { line -&gt;tmp = line.readLine().trim()}

//Groovy test if file exists
File src = new File(srcFile)
if (src.exists() ){ println "I exist"}
else{println "I don't exist"}

#Ruby openfile for reading
fh = File.new(path, "r")  # open file "path" for reading only
fh.close

#Ruby open file for writing
fout   = File.new(path, "w")  # open file "path" for writing only
fout.puts "Up, Up, Down, Down, Left, Right, Left, Right, B, A, Select, Start"
fout.close

#Ruby open file for apending
fa= File.new("DeleteMe.txt","a")
fa.puts "I am at the end of file"
fa.close

#Ruby read eachline in a file
File.open("file").each { |line| p line}

#Ruby read entire file to string
fh = File.new(filename)
str = fh.read

#Ruby read entire file into array(each line is an element in the array)
fh = File.new(filename)
str = fh.readlines

#Python Write a file
fout = open("DeletMe.txt", "w")
fout.write("Writing to fout\nCheck it out!")
fout.close()

#Python Read an entire file
fin = open("ReadingTest.txt", "r")
fin_text =  fin.read()
fin.close()
print fin_text

#Python read entire file into list
fin = open("ReadingTest.txt", "r")
txt= fin.readlines()
fin.close()
print txt[0]

#Python append to a file
fh= open ( 'DeleteMe.txt', 'a' )
fh.write ( '\n\n\nBottom line.' )
fh.close()

#Perl reading a file
open(FILE,  '&lt;', $file) or die "Can't read $file: $!\n";
while(&lt;FILE&gt;)
{
print ;
}

#Perl append to a file
open(FILE, '&gt;&gt;', $file) or    die "Can't append to $file: $!\n";
print FILE "text";
close(FILE);

#Perl read and write to a file
#+&lt; allows reading and writing, and keeps the data that was
#already in the file.  open() will fail if file doesn't exist.
open(FILE, "+&lt;$file" ) or die ("Can't  read|write: $file\n");
close(FILE);

#Perl read and write to a file
#+&gt;allows writing and reading, but replaces/overwrites the
#data in the file if the file exists. Creates it if it doesn't exist.
open(FILE, "+&gt;$file" ) or die ("Can't write or read:$file \n");

close(FILE);</pre>
</blockquote>
<p>PHP code doesn&#8217;t display properly within WordPress, so here is an image of the code</p>
<p><a href="http://javazquez.com/juan/wp-content/uploads/2008/06/phpcode.gif"><img class="alignnone size-full wp-image-10" title="phpcode" src="http://javazquez.com/juan/wp-content/uploads/2008/06/phpcode.gif" alt="PHP File I/O" width="340" height="233" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://javazquez.com/juan/2008/06/27/file-io-part-1/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Handling Ruby&#8217;s String.each_char Iterator</title>
		<link>http://javazquez.com/juan/2008/06/25/handling-rubys-stringeach_char-iterator/</link>
		<comments>http://javazquez.com/juan/2008/06/25/handling-rubys-stringeach_char-iterator/#comments</comments>
		<pubDate>Thu, 26 Jun 2008 05:50:33 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby code quirks]]></category>

		<guid isPermaLink="false">http://javazquez.com/juan/?p=7</guid>
		<description><![CDATA[Ahh the joys of iterators. I can&#8217;t say enough about how much they make my life easier. They are just so darn handy. Life was good in my Ruby world until I needed to iterate through the characters in a string. Thinking to myself, &#8220;there has got to be a method that does this,&#8221; I [...]]]></description>
			<content:encoded><![CDATA[<p>Ahh the joys of iterators. I can&#8217;t say enough about how much they make my life easier. They are just so darn handy. Life was good in my Ruby world until I needed to iterate through the characters in a string. Thinking to myself, &#8220;there has got to be a method that does this,&#8221; I looked up Ruby&#8217;s String class and saw just what the doctor ordered&#8230; <code>each_char</code>.</p>
<p> Feeling pretty proud that my favorite language had this baked right in, I was only to happy to inject it into my code and test it out. That is until I recieved the dreaded <strong>NoMethodError: undefined method `each_char&#8217; </strong>. Eeek, what did I do wrong? Did I mispell the method&#8230;..Nope, did I call it correctly&#8230;..Yep. Well, what the heck is going on? </p>
<p>After multiple attempts to find the answer on Google, I finally posted my problem to the <a href="http://groups.google.ca/group/rubyonrails-talk/browse_thread/thread/1fd48ddc22f6bfe6#">ruby-talk group. </a> I was told that the Ruby 1.8 String implementation that I was using only understood bytes and that I could use <strong>require &#8216;jcode&#8217;</strong> to get the iterator to work the way I wanted. I did some looking around and I am not sure this is a great solution, after all, I could have easily used the <strong>each_byte{|f|  f.chr}</strong> to iterate through and convert accordingly. I don&#8217;t understand why something that is documented as part of the class, does not work. </p>
<p>It would really help if there was an easy to search area on the net dedicated to language quirks for people trying to get a better grasp of their programming language of choice. Maybe that will be my next <a href="http://www.rubyonrails.org/">ROR </a>project.</p>
<p>As it turns out, my Ruby 1.8.7 installation on my <a href="http://fedoraproject.org/en/index">Fedora core 9 </a> works as advertised.</p>
]]></content:encoded>
			<wfw:commentRss>http://javazquez.com/juan/2008/06/25/handling-rubys-stringeach_char-iterator/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>

