Ruby as a first language

M

Martin DeMello

What are some of the 'fun' things someone just getting into programming
(as a hobby) could do with Ruby?

martin
 
A

Ara.T.Howard

What are some of the 'fun' things someone just getting into programming
(as a hobby) could do with Ruby?

martin

a chat program using drb.

-a
--
===============================================================================
| EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov
| PHONE :: 303.497.6469
| A flower falls, even though we love it;
| and a weed grows, even though we do not love it.
| --Dogen
===============================================================================
 
J

James Britt

Martin said:
What are some of the 'fun' things someone just getting into programming
(as a hobby) could do with Ruby?


Well, packaging systems seem to bring smiles to everyone around ....


:)



No, seriously, I've written a number of simple scripts to fetch web
pages. Usually they just construct a URL based on some command-line
input, then make a system call to launch a browser. I search Google
this way, as well as look for stuff on buy.com, check TV listings, read
the news, grep/navigate my local wiki, a few other things.

What might make this interesting for a newcomer would be to write a few
scripts like these, then see what they have in common, then see if they
can extract the common stuff into a class in an external file. I ended
up with a small class to encapsulate browser selection, url
construction, and browser launching.

Along the way, one learns how to get parameters from the command line,
validate the input, build new strings, do some basic if/then logic,
write a simple class, use 'require'.

And one ends up with actually useful tools for daily life.


James
 
G

Gawnsoft

Well, packaging systems seem to bring smiles to everyone around ....


:)



No, seriously, I've written a number of simple scripts to fetch web
pages. Usually they just construct a URL based on some command-line
input, then make a system call to launch a browser. I search Google
this way, as well as look for stuff on buy.com, check TV listings, read
the news, grep/navigate my local wiki, a few other things.

Could I see them please?

What might make this interesting for a newcomer would be to write a few
scripts like these, then see what they have in common, then see if they
can extract the common stuff into a class in an external file. I ended
up with a small class to encapsulate browser selection, url
construction, and browser launching.

Along the way, one learns how to get parameters from the command line,
validate the input, build new strings, do some basic if/then logic,
write a simple class, use 'require'.

And one ends up with actually useful tools for daily life.

--
Cheers,
Euan
Gawnsoft: http://www.gawnsoft.co.sr
Symbian/Epoc wiki: http://html.dnsalias.net:1122
Smalltalk links (harvested from comp.lang.smalltalk) http://html.dnsalias.net/gawnsoft/smalltalk
 
J

James Britt

Gawnsoft said:
Could I see them please?


Here's a simple case: google

# file g.rb
$: << File.dirname( __FILE__ )
require 'browser'

$url = 'http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF-8&q='
if ARGV.size < 1
puts "You need to enter at least one search word."
else
$url << ARGV.join("+")
$stderr.puts "Calling #{$url}"
Browser.new( 'FB' ).get( $url )
end
# end of file

Next is the code for browser.rb. It's meant to run on Windows.
I've never bothered to try it on Linux; executable paths would
have to change, as well as the calling convention (e.g., 'call
someApp.exe'), but maybe not much else. (Actually, I think the big
issue for me is that when I launch Mozilla or Firefox , and there is
already an instance running, it stupidly insists I select another
profile, or create a new one, or I can't use the new instance. That
doesn't happen on Windows.)

I believe I use a thread to launch the browser so that the script ends
and I get my command prompt back; I run my browser scripts from the
command line, like so:

C:\> g some search words

Windows handles the file extension stuff automagically, as I've added
the script directory to my PATH variable.

But, without using a thread, the script would just wait until I closed
the browser, which is annoying.

Anyway, once I put together the Browser class I needn't think about it
when I write other scripts for pulling up web sites. (And 'less
thinking' is one of the goals of coding. :) )

# browser.rb

class Browser
DEFAULT = 'FB'
CB = 'CB'
IE = 'IE'
MOZ = 'MOZ'
OP = 'OP'
FB = 'FB'

@@exe = Hash.new( 'explorer')
@@exe['IE'] = 'explorer'
@@exe['CB'] = '"E:/Program Files/Crazy Browser/Crazy Browser.exe"'
@@exe['OP'] = 'e:/Program Files/Opera7/opera.exe'
@@exe['MOZ'] = 'e:/Program Files/mozilla.org/Mozilla/mozilla.exe'
@@exe['FB'] = 'E:/MozillaFirebird/MozillaFirebird.exe '

def initialize( browser_name = Browser::DEFAULT )
@broswser = browser_name
@b_exe = select_exe( browser_name )
$stderr.puts( "Using broswer #@broswser ")
end

def get( url )
$stderr.puts( "get is using #@b_exe" )
Thread.new( url ){ |t| `call "#{@b_exe}" "#{url}"` }
end

def select_exe( bname )
@@exe[ bname ]
end

def self.get( url,
browser_name = ( @broswser ? @broswser : Browser::DEFAULT ) )
exe = Browser.new(browser_name).select_exe( browser_name )
Thread.new( url ){ |t| `start "#{exe}" "#{url}"` }
end
end


# End of browser.rb

Lookng at the code now, there's cruft and goofiness, but it works so I
haven't bothered to clean stuff up. But for a newcomer, it might be
worthwhile to try writing a class that allows the user to 1) optionally
select a particular browser to use (but have a default browser defined),
2) pass in the URL to load, 3) ensures that the script can run and
exit without having to wait until the browser closes.

Here's another script; this one calls Yahoo maps, like this:

c:\> map 11123 Main Street, Scottsdale, AZ 85251

# map.rb
$: << File.dirname( __FILE__ )
require 'browser'
$base_url = 'http://maps.yahoo.com/py/maps.py?Pyt=Tmap'

def argstr_to_qstring( str )
parts = str.split( ',', 2)
street = parts[0].strip.gsub( / /, '+')
state = parts[1].strip.gsub( / /, '+')
"&addr=#{street}&csz=#{state}"
end

def args_to_mapurl( args )
a = args.join(' ')
"#{$base_url}#{argstr_to_qstring( a )}&Get%A0Map=Get+Map"
end

if ARGV.size < 1
puts "You need to enter an address."
else
url = args_to_mapurl( ARGV )
Browser.get( url , Browser::MOZ )
end

# end of map.rb

This one is a bit gnarlier. But, once someone has written a general way
to launch a Web browser, a next step might be to explore manipulating
the input to construct more complex URLs. The goal is to make it easy
to type at the command line, and let the code do the busy work.

James
 
N

Nicholas Van Weerdenburg

Some of the programs I wrote to learn ruby (though I have sigificant
Java and C++ experience):

A command line stopwatch program when I needed to time something. Added
start/mark/stop. Then I added comments to each. Then persistence or
results with yaml. Logging with log4r. Testing with Test/Unit. Passing
commands from the command line (e.g. to start timing on startup). I
think I also ended up with a list of 40 features I wanted to add. It was
a pleasant learning program that ended up with far more features then I
would have guessed, and I think it would make a good intro/fun project.

For writing, I wrote a jnl.rb that creates a journal entry template with
today's date and then opens it in vi. That's slowly extending into a
PIM, with parseopts for command line parsing and options for using
different editors, adding an entry from the command line (--entry "blah
blah blah"), and so on. I think this would be a good learning program as
well.

Regards,
Nick
 
J

James Britt

Nicholas said:
For writing, I wrote a jnl.rb that creates a journal entry template with
today's date and then opens it in vi. That's slowly extending into a
PIM, with parseopts for command line parsing and options for using
different editors, adding an entry from the command line (--entry "blah
blah blah"), and so on. I think this would be a good learning program as
well.

I wrote something like that for myself on a recent contact job. I
wanted a way to track little issues as they came and went, so that I
could go back and see how much time was wasted dealing with WebLogic and
assorted J2EE issues. I needed some way to just tap out notes at the
command line, with date and time stamps in the text.

What makes something like that a good starting point for a newbie is
that it's simple but it offers some immediate practical value, and, once
it's working, features can gradually be added.

And when the features get out of control, one can learn refactoring, too.


James
 
J

Jason Lee

James Britt said:
I wrote something like that for myself on a recent contact job. I
wanted a way to track little issues as they came and went, so that I
could go back and see how much time was wasted dealing with WebLogic and
assorted J2EE issues. I needed some way to just tap out notes at the
command line, with date and time stamps in the text.

What makes something like that a good starting point for a newbie is
that it's simple but it offers some immediate practical value, and, once
it's working, features can gradually be added.

And when the features get out of control, one can learn refactoring, too.


James
abandonware slandered indepth gawdamned acquintance inbuilt chegwin
freebies addittion crappola contient mimeole advertizments secureway
gadalke symetric adviced adresses asmworkshop emule aignes login
beschlag convinctions alltheweb izmeni privatpolitik downloads
apologise desparation publiquement assed theregister eliteness pouche
asshole spammer email geees john mcneil babelfish upload ahold
braindead searching babesontheweb corelation betas hardball bastoids
decieb cinix couldn himherself bearly lancia forun moderator australia
beschikbaar vianello sideeffe homepage bindisplay mailboms haltabuse
kayaker bittorent gary wi brady scamming uslovii decrypted biznes
altadena wisconsin inact laura jones doomy michael peterson bookmarked
slandering ranshe tates boreing tim harding allinurl pseudonyms
groupdomain bphonebook poursuivre ssection hijacked virgina va cahoots
dawgs wouldn goodboy leganord vermont vt ccctournament availible
euskalerria cloakers chargback unodc thelist dan grubbs laters impune
clientaddr klebing spaming finche comin draad verfolgen central city
phrocrew terry hall comming workarounds weren megago crackable gatto
systran dripc crypted comcast portscan tions cyberangels
spangdelicious sendig cyberpharises inurl freeby eigent lois riggs
cybertip contrib alphabeticaly prudenter defamation gutierrez
anonymizing hagcc definitly theorical reportstalking develope oregon
or harmony padova demoscene sprouts dieses didnt occurrance pizdu
pyslsk ccmaker dismantled pdabench voyeurs tounge drugix dbpubs
crimereport valse dryers wachtwoorden lusisti eachother smokin
inanchor openssl emoticons stats discussie pretenzii daytona erik
lunsen trolling backassward hiself esmtp cybercrime deranged bitching
everytime browser iraqi cbmsv readmessa favorise webfog gardenwork
sollicitation forum ladiest zanon habes defendent forum teenz
challanging sucecess fraudelent toolz dchenka squirel scott curry
parolj gameshows telephon infominder zenful geeminee hummmmm e lunsen
chaffe gianni cyber implemention theboard tennessee gigio misrepres
vienello phonebook holdrege girlfriend rambleings messageboards
cmaster homophobe aditionally spoofing idtheft copyrighted
anticommercial skopirovat imformation cantonale javascript bitched
impartiality usefull john dahl newsgroups intro impersonator sissies
greencard qmail informations halfheartedly veronavr soglasen
intersting stottern billy parker javascripts cached intitle
tatigkeiten ointments bittorrent isreal informati andere erik van lint
judiciaire disavowed article orgaization junkmail will phillips
kompressor webhits capio localita goasia terayon algos tn wyoming wy
luser outwiegh rizome silentes weavers mailbombs follwing foolfox
cloaking mailcity stalker entangled postid malevolence honeys
handwritting cardia mckenney whilst intergov personnels mozilla
nachrichten finem ademus unodc report mzejtibue netblock arn hub
defamatory respice aljazeera netiquette bigole california ca
persistant endevor west greenwich newsarticle cybertipii uninvolved
proxies occasionaly computerwords allinanchor bookmarlets oppps
brainless doesn popups kissimmee douglas orgdate gentelman gloriuos
taire new york ny orggames forefront antichildporn pagine orglesson
referers personals trully orgto changedetect accussed javier romero
quidquid outblaze uncollated downloadable using paris
(e-mail address removed) adverts seward particularily toopliable
scammers shtml pesky econsumer tortious cognden operapl popstars
seerev webhosting ricerca menya popup passwrd porting spammed columbus
postcount fantomaster reposting presentable heshe websmoke infos psssh
hisher bullshitting kudos cotton wood publically postgresssql jazeera
jason smith puristic safetyed ethnically bookmarks reposts sergei
smith (e-mail address removed) speaketh resend marcoz iciaire quoting
rwcrmxc kazaa ccard lacessit bullshit saddam assurtions neccesarily
emails seens ddosattacked wimsnery stbtclient sensi ctions einer hummm
matt parker sergey smith ordinateur pussyfootin decompiling showpost
practises reportcp systransoft showthread filecompression netscape
tina lawson sicut newbie pissed horticulturists barrington slobo
straitjacket seperate prosto sociopath hited gomer scumbag suspect
stalkers crapmongers webhists serch stoggie herdthinners collator
huffy straylight cuius systranbox unbelievably subscribtion peepoles
studing lookover surprize smogs dijuno anals cottage grove sweatheart
comrom abreviations changedetection testerday haters politcal possibly
tiporich unwarranted treviso pffff trempack icobalt spyware encense
trollie scammer bestrebt semingly twentythree antispam frends calomnie
twpyhr yyyttt predica uncensored fernch schen sreal bethelak underage
specificaly groot tigen ungesetzlichen new york propri favia
cannonfodder unsolicited chargebacks whoelse lotsah voila untergrund
ffentlich mozhesh gainesville vorhanden anonimously femme fdemo
webmasters assur spams representitive weeding uspassword followup
grmbl kirk boyd weilding normaly tvoix cheapo welle accordace admin
pakage tammy pleskow werent download pansa ukstory combolist
whatshisname similia falsche allright wiredsafety gales seite cranston
kreditkarte wobot charset advertizing spamming xaknuli lenghty
washington wa dunno uninvited juneau zasunut basicaly mzejtibue
 
J

Jason Lee

James Britt said:
I wrote something like that for myself on a recent contact job. I
wanted a way to track little issues as they came and went, so that I
could go back and see how much time was wasted dealing with WebLogic and
assorted J2EE issues. I needed some way to just tap out notes at the
command line, with date and time stamps in the text.

What makes something like that a good starting point for a newbie is
that it's simple but it offers some immediate practical value, and, once
it's working, features can gradually be added.

And when the features get out of control, one can learn refactoring, too.


James
abandonware slandered indepth gawdamned acquintance inbuilt chegwin
freebies addittion crappola contient mimeole advertizments secureway
gadalke symetric adviced adresses asmworkshop emule aignes login
beschlag convinctions alltheweb izmeni privatpolitik downloads
apologise desparation publiquement assed theregister eliteness pouche
asshole spammer email geees john mcneil babelfish upload ahold
braindead searching babesontheweb corelation betas hardball bastoids
decieb cinix couldn himherself bearly lancia forun moderator australia
beschikbaar vianello sideeffe homepage bindisplay mailboms haltabuse
kayaker bittorent gary wi brady scamming uslovii decrypted biznes
altadena wisconsin inact laura jones doomy michael peterson bookmarked
slandering ranshe tates boreing tim harding allinurl pseudonyms
groupdomain bphonebook poursuivre ssection hijacked virgina va cahoots
dawgs wouldn goodboy leganord vermont vt ccctournament availible
euskalerria cloakers chargback unodc thelist dan grubbs laters impune
clientaddr klebing spaming finche comin draad verfolgen central city
phrocrew terry hall comming workarounds weren megago crackable gatto
systran dripc crypted comcast portscan tions cyberangels
spangdelicious sendig cyberpharises inurl freeby eigent lois riggs
cybertip contrib alphabeticaly prudenter defamation gutierrez
anonymizing hagcc definitly theorical reportstalking develope oregon
or harmony padova demoscene sprouts dieses didnt occurrance pizdu
pyslsk ccmaker dismantled pdabench voyeurs tounge drugix dbpubs
crimereport valse dryers wachtwoorden lusisti eachother smokin
inanchor openssl emoticons stats discussie pretenzii daytona erik
lunsen trolling backassward hiself esmtp cybercrime deranged bitching
everytime browser iraqi cbmsv readmessa favorise webfog gardenwork
sollicitation forum ladiest zanon habes defendent forum teenz
challanging sucecess fraudelent toolz dchenka squirel scott curry
parolj gameshows telephon infominder zenful geeminee hummmmm e lunsen
chaffe gianni cyber implemention theboard tennessee gigio misrepres
vienello phonebook holdrege girlfriend rambleings messageboards
cmaster homophobe aditionally spoofing idtheft copyrighted
anticommercial skopirovat imformation cantonale javascript bitched
impartiality usefull john dahl newsgroups intro impersonator sissies
greencard qmail informations halfheartedly veronavr soglasen
intersting stottern billy parker javascripts cached intitle
tatigkeiten ointments bittorrent isreal informati andere erik van lint
judiciaire disavowed article orgaization junkmail will phillips
kompressor webhits capio localita goasia terayon algos tn wyoming wy
luser outwiegh rizome silentes weavers mailbombs follwing foolfox
cloaking mailcity stalker entangled postid malevolence honeys
handwritting cardia mckenney whilst intergov personnels mozilla
nachrichten finem ademus unodc report mzejtibue netblock arn hub
defamatory respice aljazeera netiquette bigole california ca
persistant endevor west greenwich newsarticle cybertipii uninvolved
proxies occasionaly computerwords allinanchor bookmarlets oppps
brainless doesn popups kissimmee douglas orgdate gentelman gloriuos
taire new york ny orggames forefront antichildporn pagine orglesson
referers personals trully orgto changedetect accussed javier romero
quidquid outblaze uncollated downloadable using paris
(e-mail address removed) adverts seward particularily toopliable
scammers shtml pesky econsumer tortious cognden operapl popstars
seerev webhosting ricerca menya popup passwrd porting spammed columbus
postcount fantomaster reposting presentable heshe websmoke infos psssh
hisher bullshitting kudos cotton wood publically postgresssql jazeera
jason smith puristic safetyed ethnically bookmarks reposts sergei
smith (e-mail address removed) speaketh resend marcoz iciaire quoting
rwcrmxc kazaa ccard lacessit bullshit saddam assurtions neccesarily
emails seens ddosattacked wimsnery stbtclient sensi ctions einer hummm
matt parker sergey smith ordinateur pussyfootin decompiling showpost
practises reportcp systransoft showthread filecompression netscape
tina lawson sicut newbie pissed horticulturists barrington slobo
straitjacket seperate prosto sociopath hited gomer scumbag suspect
stalkers crapmongers webhists serch stoggie herdthinners collator
huffy straylight cuius systranbox unbelievably subscribtion peepoles
studing lookover surprize smogs dijuno anals cottage grove sweatheart
comrom abreviations changedetection testerday haters politcal possibly
tiporich unwarranted treviso pffff trempack icobalt spyware encense
trollie scammer bestrebt semingly twentythree antispam frends calomnie
twpyhr yyyttt predica uncensored fernch schen sreal bethelak underage
specificaly groot tigen ungesetzlichen new york propri favia
cannonfodder unsolicited chargebacks whoelse lotsah voila untergrund
ffentlich mozhesh gainesville vorhanden anonimously femme fdemo
webmasters assur spams representitive weeding uspassword followup
grmbl kirk boyd weilding normaly tvoix cheapo welle accordace admin
pakage tammy pleskow werent download pansa ukstory combolist
whatshisname similia falsche allright wiredsafety gales seite cranston
kreditkarte wobot charset advertizing spamming xaknuli lenghty
washington wa dunno uninvited juneau zasunut basicaly mzejtibue
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top