Forum: Ruby Good Ruby Examples?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
hcatlin (Guest)
on 2005-12-01 16:20
(Received via mailing list)
I'm planning on doing a tutorial about Ruby for Ryerson University's CS
Majors group. No one here knows anything about Ruby, so I thought it'd
be a great way to evangelize a bit. I'm always surprised how few
students actually code at all on their own. Most of them know Java and
C from class, but find them to be nothing more than class projects.

What I'm asking you guys for is if you have any short code ideas that
can be programmed *really* quickly in Ruby that might illustrate its
versatility. Some code example that would be hell to write in other
languages that would be interesting for an hour long explaination. I'd
say about 20 to 30 lines or so.

So, what's everybody's favorite smallish examples of the power of
coding with Ruby.

-hampton.
vanek (Guest)
on 2005-12-01 17:17
(Received via mailing list)
C has 'Hello world!'
Ruby has the proverbial 'ToDo' list,
	http://manuals.rubyonrails.com/read/book/7
james_b (Guest)
on 2005-12-01 18:02
(Received via mailing list)
Lou V. wrote:
> C has 'Hello world!'
> Ruby has the proverbial 'ToDo' list,
>     http://manuals.rubyonrails.com/read/book/7

Except the typical C "Hello, world" example doesn't start with, "First,
download and install a set of libraries that does all the interesting
bits."

For a small example, show the use of blocks.  Give a Rake demo, then
examine the Rake lib code that mkaes it possible.

Maybe go through the code of Jim W.'s Builder library, or something
else that shows the power of method_missing and dynamic code invocation.


James

--

http://www.ruby-doc.org       - Ruby Help & Documentation
http://www.artima.com/rubycs/ - Ruby Code & Style: Writers wanted
http://www.rubystuff.com      - The Ruby Store for Ruby Stuff
http://www.jamesbritt.com     - Playing with Better Toys
http://www.30secondrule.com   - Building Better Tools
Jules J. (Guest)
on 2005-12-01 18:19
If you want to show them how fun ruby is: start with a c/java program
and translate it to ruby step-by-step.
Like this one:
http://onestepback.org/articles/groovy/ajavaprogram.html

Maybe something like:

a = false
puts ('aa'..'zz').select{a = !a}

prints:
aa
ac
ae
etc.

Will be huge in java ;-)

This can be an introduction, but you need a practical example too.
James G. (Guest)
on 2005-12-01 19:02
(Received via mailing list)
On Dec 1, 2005, at 9:57 AM, James B. wrote:

> Lou V. wrote:
>> C has 'Hello world!'
>> Ruby has the proverbial 'ToDo' list,
>>     http://manuals.rubyonrails.com/read/book/7
>
> Except the typical C "Hello, world" example doesn't start with,
> "First, download and install a set of libraries that does all the
> interesting bits."

I agree.  Avoid introducing 50 great add-on tools and target language
basics.

> For a small example, show the use of blocks.

Amen.

I was reading a Java book this morning that talked about the Visitor
Design Pattern (pretty block-like) as the root of all evil in the
world.  I actually got mad reading the text.  Now I realize, they
just don't "get it"...

> Give a Rake demo...

Wait, didn't we just get back to downloading libraries?  ;)  (I'm
kidding around here.  It's a fine idea.)

Perhaps there's a decent topic, or just some inspiration, hiding in
the Ruby Q.zes (http://rubyquiz.com/).  Of course, we know I'm
biases there.

James Edward G. II
curtis.schofield (Guest)
on 2005-12-01 19:11
(Received via mailing list)
>
> I was reading a Java book this morning that talked about the Visitor
> Design Pattern (pretty block-like) as the root of all evil in the
> world.  I actually got mad reading the text.  Now I realize, they
> just don't "get it"...

Java, not supporting double-dispatch, can turn a pretty pattern like
Visitor into a mess.
vanek (Guest)
on 2005-12-01 19:19
(Received via mailing list)
James B. wrote:
> Lou V. wrote:
>
>> C has 'Hello world!'
>> Ruby has the proverbial 'ToDo' list,
>>     http://manuals.rubyonrails.com/read/book/7
>
>
> Except the typical C "Hello, world" example doesn't start with, "First,
> download and install a set of libraries that does all the interesting
> bits."

Good point. You get to show what a rich set of libraries Ruby has and
how easy libraries can be installed with just one command. Thanks for
pointing that out.

-lv


[snip]
james_b (Guest)
on 2005-12-01 19:35
(Received via mailing list)
James Edward G. II wrote:
> On Dec 1, 2005, at 9:57 AM, James B. wrote:
>
>> Give a Rake demo...
>
>
> Wait, didn't we just get back to downloading libraries?  ;)  (I'm
> kidding around here.  It's a fine idea.)
>

The idea is to give a Rake demo, and then examine the Rake library code
itself as the real example of Ruby.  No hand waving (which a Rake demo
alone would entail); show how Ruby lends itself to robust, high-level
abstractions (such as Rake tasks).



James
--

http://www.ruby-doc.org       - Ruby Help & Documentation
http://www.artima.com/rubycs/ - Ruby Code & Style: Writers wanted
http://www.rubystuff.com      - The Ruby Store for Ruby Stuff
http://www.jamesbritt.com     - Playing with Better Toys
http://www.30secondrule.com   - Building Better Tools
james_b (Guest)
on 2005-12-01 19:39
(Received via mailing list)
Lou V. wrote:
>> Except the typical C "Hello, world" example doesn't start with,
>> "First, download and install a set of libraries that does all the
>> interesting bits."
>
>
> Good point. You get to show what a rich set of libraries Ruby has and
> how easy libraries can be installed with just one command. Thanks for
> pointing that out.

A valuable aspect of Ruby and gems, but it says nothing about the
language per se.

I'd be wary of emphasizing the "rich set of libraries" aspect, too, as
Python, Perl, and Java probably have Ruby beat.

Better to show how much one can do, and how easily, without extra
libraries.

Ruby's biggest selling point is Ruby itself.


James
--

http://www.ruby-doc.org       - Ruby Help & Documentation
http://www.artima.com/rubycs/ - Ruby Code & Style: Writers wanted
http://www.rubystuff.com      - The Ruby Store for Ruby Stuff
http://www.jamesbritt.com     - Playing with Better Toys
http://www.30secondrule.com   - Building Better Tools
martin.ankerl (Guest)
on 2005-12-01 20:28
(Received via mailing list)
> So, what's everybody's favorite smallish examples of the power of
> coding with Ruby.

This is my favourite, here are two solutions for the task
"Write a threaded server that offers the time"
(Ruby example is taken from the book 'The Ruby Way'):


# Ruby
require "socket"

server = TCPServer.new(12345)

while (session = server.accept)
   Thread.new(session) do |my_session|
     my_session.puts Time.new
     my_session.close
   end
end




// And the functional equivalent in Java:
package at.martinus;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class TimeServer {
   private static class TellTime extends Thread {
     private Socket soc;

     public TellTime(Socket soc) {
       super();
       this.soc = soc;
     }

     public void run() {
       try {
         this.soc.getOutputStream().write(new
Date().toString().getBytes());
       } catch (Exception e) {
       } finally {
         try {
           this.soc.close();
         } catch (IOException e1) {
         }
       }
     }
   }

   public static void main(String args[]) throws Exception {
     ServerSocket server = new ServerSocket(12345);
     while (true) {
       new TellTime(server.accept()).start();
     }
   }
}
christopher.mcmahon (Guest)
on 2005-12-01 22:46
(Received via mailing list)
I'm not sure what level your students are, but a demo of drivting
Internet Explorer with the Watir project code
(http://wtr.rubyforge.org) is colorful and fun.  Advanced students can
investigate the Watir libraries and discuss Domain Specific Languages;
less advanced students can investigate the Watir unit tests and
examples quite easily.   For instance, the code below is from the Watir
distribution and tests Google Maps:

require 'watir'
include Watir
require 'test/unit'

class TC_google_maps < Test::Unit::TestCase

    def test_google_maps

        testSite = "http://maps.google.com"
        ie = IE.new
        ie.goto(testSite)
        ie.text_field(:id,"q").set("Durango,CO")
        ie.button(:index, 1).click

        matchlat = '37.275278'
        matchlong = '-107.879444'

            assert_match(matchlat,ie.frame("vp").html.to_s)
            assert_match(matchlong,ie.frame("vp").html.to_s)
    end
end
leavengood (Guest)
on 2005-12-01 23:59
(Received via mailing list)
How about an application which uses open-uri or Net::HTTP to download
all the files of a particular type from a web-page? For example, all
the images, or all the linked images, or all the linked mp3 files, or
whatever. I'd recommend just using regular expressions for the HTML
parsing, since that will show the power of regular expressions and
will also avoid the potential of Ruby XML parsing libraries barfing on
bad HTML.

The URI library can be used to handle relative URLs, etc.

This will be a good demo, and useful too.

Another option is a bulk-downloader that takes special URLs like
http://www.somesite.com/images/image_[01-25].jpg to get all the images
from image_01.jpg to image_25.jpg.

Ryan
hcatlin (Guest)
on 2005-12-02 00:07
(Received via mailing list)
James, that's more what I'm thinking about.

Less libraries, and more how powerful its paradigms are. Especially its
unique syntax and how readable it is (when done right).

Thanks everyone for your suggestions though. They are very good.
Digikata (Guest)
on 2005-12-02 02:05
(Received via mailing list)
Since the audience is composed of CS majors, some classic algorithms in
ruby vs java or C might be in order. Also you might show them the
buildup of a multi-level data structure, then dump and retrieve using
yaml...
Paul M. (Guest)
on 2005-12-02 04:18
(Received via mailing list)
Show them the basics of the language, ALA  "Ruby in a Nutshell".
Let them loose with irb & ri.
nightphotos (Guest)
on 2005-12-06 07:43
(Received via mailing list)
Hi Hampton,

> What I'm asking you guys for is if you have any short code ideas that
> can be programmed *really* quickly in Ruby that might illustrate its
> versatility. Some code example that would be hell to write in other
> languages that would be interesting for an hour long explaination.

My favorite is the well-known quicksort algorithm:

def quicksort(a)
  return a if a.size <= 1
  pivot = a[0]
  quicksort(a.select {|i| i < pivot }) +
            a.select {|i| i == pivot } +
  quicksort(a.select {|i| i > pivot })
end

quicksort is "hell" to write in C or C++ unless you're extremely clever.

Wayne V.
No Bugs Software
"Ruby and C++ Agile Contract Programming in Silicon Valley"
han.holl (Guest)
on 2005-12-06 17:19
(Received via mailing list)
On 12/6/05, Wayne V. <removed_email_address@domain.invalid> wrote:
>             a.select {|i| i == pivot } +
>   quicksort(a.select {|i| i > pivot })
> end
>
> quicksort is "hell" to write in C or C++ unless you're extremely clever.
>
> Wayne V.
> No Bugs Software
> "Ruby and C++ Agile Contract Programming in Silicon Valley"
>
>
And then demonstrate how this actually works with all kinds of objects
that
implement the comparison operators .
Nice duck typing example.

Han
surrender_it (Guest)
on 2005-12-06 19:50
(Received via mailing list)
Wayne V. ha scritto:
>
> def quicksort(a)
>   return a if a.size <= 1
>   pivot = a[0]
>   quicksort(a.select {|i| i < pivot }) +
>             a.select {|i| i == pivot } +
>   quicksort(a.select {|i| i > pivot })
> end
>
> quicksort is "hell" to write in C or C++ unless you're extremely clever.

you may appreciate Enumerable#partition:
def qs(a)
   return a if a.size <=1
   pivot = a.shift
   less, more = a.partition{|y| y < pivot}
   qs(less) + [pivot] + qs(more)
end
logancapaldo (Guest)
on 2005-12-07 07:02
(Received via mailing list)
On Dec 6, 2005, at 12:47 PM, gabriele renzi wrote:

>>   pivot = a[0]
>   pivot = a.shift
>   less, more = a.partition{|y| y < pivot}
>   qs(less) + [pivot] + qs(more)
> end
>
>
>

I don't know, if you start throwing partition in there, you're this
close to just saying a.sort
This topic is locked and can not be replied to.