Browse | Submit A New Snippet | Create A Package

 

Snippets by language: Ruby

Snippet ID Title
Packages Of Snippets2hatenabmdrawnboy
Hatena Bookmark AtomAPI binding for Ruby.
3libvalidtypesbabu proof
User Input Validation Framework
4rubypkgJayen Chandra
rubypkg
5File Splitter and JoinerSaajan N
File Splitter: Split a big file into a number of smaller files

File Joiner: Join all your "piece" files into a single file again
36motallyMotally Inc.
motally tracker for websites, easy to integrate
8AjaxTreesur max
Sample Rails application for Ajax based drag drop tree.
22Rails PG ProceduresScott Noel-Hemming
Used to create Stored Procedures and adding Trigger Functions to tables in a PostgreSQL database in Rails.
28Useful Ruby ExtensionsJames Schneider
Various extensions to core and standard libraries.
32Remove StripAmit Agarwal
To remove strip in column from the model
33Language Numberszhang bee
Some kinds of Numbers are in English!
38Surd arithmeticDick Pountain
Permits arithmetic using irrational roots in symbolic form, like √2 or 3+√5 from a Ruby program.
39Surd arithmeticDick Pountain
Let's you return values including irrational roots like √2 or 3+√5 from a Ruby program, by defining a class Surd.
40justinjustin stultz
it will be about me and my life
41nike shoesjustin stultz
all about shoes
452008ming xu
981321
46Simple codeSerheo Shatunov
Simple rails code. designless to-do list.
50MS word document manipulationCici Wirachmat
Some snippets written by James Toomey in this ruby-talkposting: http:blade.nagaokaut.ac.jp/cgi-bin/scat-rb/ruby/ruby-talk/60004
51RubySnipsLarry Kite
Snippets of Ruby
52virtapayCici Wirachmat
Business Website using Ruby on Rails
57Free Microsoft Points Codes 2012 ReleaseBetty Green
http://getfreemicrosoftpointscodes2011.blogspot.com/2012/02/free-microsoft-points-codes-2012.html
75Well_BeingJyoti Kakarala
Well Being
76laplaceWictor Borisov
Laplace transform inverse
77laplaceWictor Borisov
Laplace transform inverse
78laplaceWictor Borisov
Laplace transform inverse
Snippets
1hash to structDaniel Berger
A method to convert a Hash into a Struct
2Deep CopyMatthew Linnell
A deep copy mechanism used by many rubyists (I by no means claim original authorship of this one, it's just darn useful to have posted here!)
3Fuzzy MatchMatthew Linnell
A (rough) fuzzy match mechanism for strings. Returns 0 <= score <= 1.
6Parse one XML element from a fileTom Copeland
Parses one XML element out of a given file
5linecatDavid Dembinski
Two ways to read stdin one line at a time, concatenate the results, strip the newlines, and return the results to stdout.
7MS Word document manipulationTom Copeland
Some snippets written by James Toomey in this ruby-talk posting:

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/60004

8Commify a numberTom Copeland
Commifies a number. Preserved from Warren Brown's ruby-talk posting here - http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/78103.
9DS3C3David Dembinski
Discordian Society Super Secret Cryptographic Cypher Code
17Worlds simplest SQL Server (or MSDE) query codeRalph Mason
This is a very simple way to run a quick query on a sql server. The machine must have the sql server client tools installed (or MSDE)
11Randomizing an ArrayFlorian Groß
Randomizes the elements of an Array.
12Observable attributeJim Menard
Defines attr_observable which creates reader and writer methods for a symbol and includes the Observable module if not already done so. The writer method calls the methods Observable.changed() and Observable.notify_observers().
13Windows RegistryRodrigo Bermejo
Check if a given software is installed on the local machine.
For more information about Registry manipulation look at 'win32/registry.rb'

15NamesCharles Hixson
A quite simple hash lookup that is used with sparsearray.
(re: formatting. It looks best with 3 spaces for tabs)
16multi-dimensioned sparse arrayCharles Hixson
This multi-dimensioned sparse array is due to a discussion on comp.lang.ruby.
This snippet depends on the names.rb snippet which was submitted separately.
19Win32::PrintDavid Naseby
A wrapper around the Win32 Print related functions.
20[ 2 , 4 ] * [ 5, 5 ]Rodrigo Bermejo
Array multiplication
22Why the luck stiff's "Object Aorta"Dima Sabanin
From Why's blog:
* Lovely, Simple, Prismatic
I say it's prismatic because this little snippy marries a few of my true loves together. Allow users to edit Ruby objects in YAML using your editor of choice.
25SuperStructHal Fulton
It's an ordered indexable collection that
allows you to access members by accessors as
well as other features.

Like a combination of Array, Hash, Struct,
OpenStruct, and maybe one or two others.
26Clear/delete all Internet Explorer cache filesZoran Lazarevic
"del_cache" is a free software that clears/deletes all Internet Explorer cache files. It is also a demonstration of using Win32 API from Ruby.

Also at: http://lazax.com/software/del_cache/del_cache.html
30Small talk like if branchesLogan Capaldo
This is a silly exercise in madness. It adds Smalltalk like branching syntax, ie:
(1 == 1).IfTrue { puts "Ok" }
you can even do
(1 == 1).IfTrue { puts "Ok" } .IfFalse { puts "Something is wrong." }
31Persistant IRB Command HistoryMichael Granger
Putting this snippet in your home directory's .irbrc will save the last 100 lines of history to a file, and reload it when IRB starts again.

It only works if you run IRB with the readline extension, and you may have to tweak it for non-Unix-ey platforms.
29Second simplest json parser in the universeRalph Mason
This is a json parser for Ruby in one line. See http://www.json.org for details about json.

You can express the full parser using this one line:

null=nil; jsonobj = eval(json.gsub(/(["'])\s*:\s*(['"0-9tfn\[{])/){"#{$1}=>#{$2}"})


LIMITATION: strings with only a : and whitespace will be turned into strings of =>
32cmdwatch - repeat a command in a curses windowSteven Jenkins
This little script takes an interval in seconds and a command as arguments. It opens a curses window, displays the command output in the curses window, sleeps for the interval, clears the window, and repeats the command. Try 'cmdwatch 5 ping -c 1 -q rubyforge.org'.
33Convert MD5 hash from Hex to Base64 encodingAndres Andreu
This function takes a hex encoded MD5 hash and converts it to a base64 encoded representation.
35grace - Alternate view on "strace" output.John Carter
The linux "strace" facility is incredibly useful, but sometimes I find it a bit hard to see what is going on. So I run "strace -o logfile programName" and then run it through my "grace < logfile" filter to give an alternate view.
36Database backupMatthew Linnell
The following script can be used to backup all/part of the contents of a database into a flat text file, by building all the necessary "insert" statements. Useful for backing up specific tables in a DB, or a quick transfer of a DB from one location to another.
37Generic #== methodZakaria Haris
A Module to include that define #==, #hash and #eql?. Useful for Object that needs to be unit tested.

This is Robert Klemme solution for question in ruby-talk:103977

Please note that the #hash is not the same if the object has hash attribute because {'a' => 1}.hash != {'a' => 1}.hash
39BatchFileEditorJames McCarthy
Great IO example,
(IMHO)
Replaces simple characters with other ones in files of type specified
Meant for *nix.
My first working Ruby code.
40New PostgreSQL database & tables through RubyJames McCarthy
Creating a database in postgreSQL through Ruby
and creating tables within that database
41Simple date manipulation examplesJames McCarthy
Howto use & manipulate dates in Ruby.
44struct to hashKevin Howe
A method to convert a Struct into a Hash
45IRB as a shellLogan Capaldo
This goofy thing lets you use irb as a shell, of sorts

Usage:
irb(main):001:0> ls "-l", "--color=auto"

46rapt - Debian Apt wrapper script Alan Chen
A ruby frontend combining many commonly used apt/dpkg commands into one command-line script
47MispelJohn Carter
Searches through all defined symbols for near misses in namespace. Hopefully some of those listed will be mispelling bugs.

Usage :-
ruby -w Mispel.rb

Will run its unit tests.

ruby -rmodule1 -rmodule2 -rmodule... Mispel.rb --cache

Will create ~/.mispel_ignore, a list of known near misses in the
system and in those modules.

If you add into your script, after all require statements...

require 'Mispel'
Mispel::problem_cases
exit(1)

It will (after a long time) print out all near misses in namespace
that are not in ~/.mispel_ignore
48Mail List HTTP Link Extractor/UploaderTimothy Hobbs
Extracts http links from a POP account, where the sender is defined, usually, as a mail list address. It creates an HTML file of the links and uploads the HTML page to your web site via FTP.
49Web Site Indexer/UploaderTimothy Hobbs
Recursively indexes all pages in your local PC web site tree based on a keyword set, creates an XML index file and uploads it to your web site.
50Diff Mode Web Site UpdaterTimothy Hobbs
Recursively checks the modification time/date of files in your local PC tree that have changed in the last 'X' hours and uploads them by FTP to your web site.
51Array[Array] & Array.slice(Array) std-lib extensionJannis Harder
Takes a list of indices and returns the corresponding items

arrayB[arrayB] == [arrayA[arrayB[0]],arrayA[arrayB[1]],....]

Example:
["Hello","World","foo","bar","baz"][[4,0,2,3,1,3,4]]
=>["baz", "Hello", "foo", "bar", "World", "bar", "baz"]

[0,1,2,3,4,5,6,7,8,9].slice([9,5,4,3,2,1,6,5,2])
=> [9, 5, 4, 3, 2, 1, 6, 5, 2]
54Binary SearchErnest Ellingson
Performs a binary search on a Ruby array. It does this by adding a function find to the Array class
57latexnotesLogan Capaldo
A small script I wrote that for the purposes of
taking notes that I in class and converting them to a more readable format. It allows you to use LaTeX markup for equations. It takes the input a creates a directory containing your notes transformed into (very bad, but simple) html and a series of .png's representing the output of your equation markup.

An example input file might be:

$ cat 2005-02-17
For this problem we will look at the equation
$ \displaystyle \int { 2 ^ { x } dx } $


I've gotten pretty quick at typing the markup and it looks much neater than my handwriting.
It requires RMagick, and also erb. (yes erb is overkill, but if you know LaTeX better than me you can probbaly do some cooler things with this) and latex installed on your system. Its a snippet cause its not very good.

This is public domain.
56Wrapper Class for WM_SETTINGCHANGESteve Callaway
Utility class to force a WM_SETTINGCHANGE message.

Example usage: To force the Win32 environment variables set with (for example) setx.exe to be immediately available to top level windows without need for a reboot.
58Filenames to 7-bit ASCIIKaspar Schiess
Convert all directories and files under a given path to contain only 7-bit ascii.
Transliteration is done trough a easy to expand lookup table.
To commit things, replace FileUtils::DryRun with FileUtils
59Duplicate a fileDevin Bayer
will duplicate original file number times
60ruby whichBruno Carnazzi
which command ruby equivalent
61Processing an array of regexpsSteve Callaway
This is a simple outline function to demonstrate how easy it is to process an array of multiple regexps inside a single block of code to evaluate matches.
62XBase/DBase Reader classLyndon Samson
A class to allow access to DBase DBF files.
63Ring Menu SystemVince Marra
This is a custom ring menu system, by LoneWolf, for the RMXP.
64Ring Menu SystemVince Marra
This is a custom ring menu system, by LoneWolf, for the RMXP.
65Ring Menu SystemVince Marra
This is a custom ring menu system, by LoneWolf, for the RMXP.
66Ring Menu SystemVince Marra
This is a custom ring menu system, by LoneWolf, for the RMXP.
67Lists methods of objects in IRBAssaph Mehr
Gives a quick list of an objects methods.

Useful in IRB and breakpoint. Just put this in your ~/.irbrc
68dynamic hash-treeHarro L
This component stores objects in a tree structure, creating nodes automatically when needed.
69objdump wrapperjason mclaughlin
This is a ruby script that formats the output of objdump to aid in reverse engineering a program.

It will label all functions, calls to functions, addresses a function is called from, addresses code is jumped from, references to string literals, and system calls.

It was inspired by a similar but less capable Perl script.

Sorry it's not very efficient, it was my first attempt at coding Ruby, and object oriented programming too.
70MemoryProfile.rbJohn Carter
On exit reports on memory hotspots.

Save it as MemoryProfile.rb

then run your code like so...

ruby -w -r MemoryProfile.rb your_code.rb

Yip, it's that easy
71Expand environment variablesStefan Lang
Expand environment variables of the form $VARIABLE in strings, like a shell.

Can be used as standalone script (behaves like echo) or with require.
75cdrpgsql.cgiBalwinder S Dheeman
To view Asterisk's call detail records from PGSQL database via web.
78RingBufferDirk Detering
A ring buffer class.
Once initialised with a specific size, every 'push' adds to the end of the buffer, while dropping the first element if size was exceeded.

79WinGrepDirk Detering
A Grep command showing preceding and following lines of a match too.

It additionally requires the RingBuffer to be found at:
<a href="http://rubyforge.org/snippet/detail.php?type=snippet&id=78";>RingBuffer code snippet</a>
80mini test (simple unit tester)meinrad recheis
a really simple but nice testing utility. of course it includes its own unit test.

setting up a testcase for your module is really simple. for example the following test case tests the reverse method of String:

require "minitest"
test("testing String#reverse"){
"henon".reverse=="noneh"
}

when running the test you will get:

testing String#reverse
OK

have fun!
76cdrfile.cgiBalwinder S Dheeman
To view Asterisk's call detail records from CSV file via web.
77config.rbBalwinder S Dheeman
Class to read/write config files with [sections], keywords = value pairs.
81CoReturnScott Bronson
If a function returns via coreturn, execution resumes at the coreturn statement rather than starting over at the top.
82PriorityQueueJoel VanderWerf
Maintain a threadsafe priority queue. Priority is assigned when pushing. Pop removes the highest priority element.
Requires rbqueue. Includes test.
83Debian Package ExplorerRichard Cole
The beginnings of a package to explore debian packages. It uses the libqt0-ruby1.8 and libdpkg-ruby.

It shows how to make a simple application using ruby qt.

A much better interface would export the debian package stuff into an RDF store and provide a faster and more searchable app, this is simply a code snippit.

I hope you find it usefull.
85filesystem recursive deletionGary Shea
A simple script for recursive deletion of a directory. Deletes everything. Originally written to use for a 'clean' target in Rake. The code that actually does the deletion is commented out. Try it. If you decide you trust it, remove the 'puts' and uncomment the File.delete.

Enjoy!
86long argument list parserruy jauregui
This snippet manages a long list of arguments given to a ruby program. It recognizes 2 flags, "-l" which calls a "ls" command to be run and gives the result as arguments to the program and "-f filename" which reads the lines in "filename" and gives the result as arguments. If no flags are given it takes the standard ARGV array.
The resulting argument list is given in an array called @lis.
87File RecursiveFelix Sun
To get every file in the given folder include subfolder.
88MyVarsDevin Mullins
Prints local, instance, and class variables. Useful in an irb or ruby/breakpoint debugging session.
89Range SumRobert Myers
function that returns the sum of every number within a range, without the use of looping.
91Convert colon separated time to secondsMichael Vera
Take a colon separated time (e.g. 10:02) and convert it to seconds. This is useful for UNIX systems where CPU time in `ps` may be displayed as 1:10:02 in the CPU which equates to 4202 seconds.
92Primes / FactoringJustin Smith
A class which provides a listing of primes, via an "each" method.
Also provides a function to produce the prime factors of a given number.

Feedback is welcome.
93Instant IntentChiaro Scuro
These poor man's "testing" functions allow you to express the intent of a piece of code and later run a reality check against it.

example:

expect 5, (3+2)

(3+2).should_be 5

expect_exception (StandardError){
puts 5/0
}

94RUDL :undefined function fixedolamide bakre
This fix the problem with RUDL.so when it looks for the print_centered function, it will not crash
95Duplicate PHP's print_r functionKevin Baird
Adds a print_r method to Object. Useful for debugging. Reconfigures itself for either Ruby1.6 or 1.8 as needed.
97WeBrick with .rhtml FilesFriedrich Fahnert
I was planning on using WeBrick for my own project, and was surprised to find out that by default it did not support erb files. It wasn’t clearly documented how to add support for ERB, but I found a solution.
<BR/>
To make .rhtml work it is necessary to override the do_GET method, so that it sets the correct mime type. The name of the file is hidden in the res.filename variable.
99Ruby code to fill in unmatched bracesKaushik Ghose
BibTeX can be screwed up by an unmatched number of braces appearing in the value of a field. This code goes through a string and inserts opening braces (when it finds an unmatched closing brace) or closing braces (cumulated at the end) to the string.
102mkfavoritiesBalwinder S Dheeman
Create a Favorities tree for IE from your Firefox's bookmarks.html file.
101Tiny Encryption AlgorithmJeremy Hinegardner
This is a pure ruby implementation of the Tiny Encryption Algorithm (TEA) by David Wheeler and Roger Needham of the Cambridge Computer
Laboratory.
103Ruby Chat ServerChristopher Kruse
Runs a Chat Server on port 7680. Fairly basic, works with telnet to send/receive. Start to a project I'm thinking about doing over the summer.
104Commify a NumberCraig Kim
A convenient function to commify a number or number string using Tom Copeland's snippet. Examples:

irb(main):009:0> commify(123456)
=> "123,456"
irb(main):010:0> commify('123456')
=> "123,456"
irb(main):011:0> commify('123456','_')
=> "123_456"
irb(main):012:0> commify(123456,'_')
=> "123_456"
105File SplitterSaajan N
File Splitter: Split a file into a number of smaller pieces
106File JoinerSaajan N
File Joiner: Join all your "piece" files into a single file again
107convert time in seconds to uptimeErik Hollensbe
This will take a time in seconds (for instance, from a delta of Time.now.to_i at two different times), and convert that to a number of days, hours, minutes, and seconds.

Note: if you want to add weeks and so on, merely figure out the magic number for that amount and put it at the head of the list, the loop will figure it out.

108String XORDag Odenhall
Allows to XOR together two strings. The main reason for doing so is for simple encryption.

"foo" ^ "xy" #=> "\036\026\027"
"\036\026\027" ^ "xy" #=> "foo"

Note that

"\000\000\000" ^ "key" #=> "key"

as a result of how XOR works.
109QuickSortSteve Shuer
a pure ruby quicksort implementation
110Create package for release on rubyforgeSoemirno Kartosoewito
Creates packages from a tag in the sourcetree.
113Simple Actions for Rails ControllersChristian Romney
DRY up controllers by metaprogramming empty action definitions to preserve the ability to use layouts.
112SHOUTcast Stream SaverLeonardo Guilherme de Freitas
Save streams of shoutcast radios with song title.
Songs will be saved in the script directory.
114assert_change/assert_no_changeMatthew Abonyi
Asserts that what is returned by an object's method has or has not changed. Inspired by assert_difference/assert_no_difference.
116Simple EncryptionDavid Love
This class allows you to encrypt strings using Rinjdael encryption routine provided in the ruby crypt library (http://crypt.rubyforge.org/installation.html). The encrypted string can also be passed in the url.
117WEBrick Reverse Proxy ServerRichard Kernahan
The reverse proxy server allows webrick to proxy one or more private servers.
For example, the URL /pear/index.html could be redirected to http://localhost:8081/pear-app/index.html while all other paths not matching the /^pear/ pattern are served normally.
120SRK/T calculationLuke Herbert
Command line script for working out IOL power given K readings, axial length and a-constant. Offered with no promise of accuracy for the interested ophthalmologist to play with (eg cross checking stuff for audit) - not for clinical use. New to ruby - style probably aweful!
121Ruby as a shell: take 2Jordan Callicoat
A little experiment inspired by snippet #45. Just a proof-of-concept really.
123KELKO::DATA::Treekelko
a simple "tree":
- nodes (being named) have multiple nodes or leaves
- leaves have also names
- the tree is "hold" on the root node
a node (means the whole tree also) can be 'collapsed'
- means all nodes without other nodes and leaves are deleted
- if the parent-node is 'empty' afterwards as well it is deleted also
- only the root-node is never deleted
inner nodes may have leafs also, not only outer nodes
124KELKO::DATA::BstarTreekelko
an implementation of a so-called B*-Tree
125KELKO::DATA::Bufferkelko
a small buffer
126KELKO::TOOLS::PWgenkelko
a generator for random 'passwords'
127KELKO::DATA::Queuekelko
a simple queue implemented using an array
128FileUtils.cp_r wrapper for patching a tree of filesAlbert Davidson Chou
A convenience script wrapping FileUtils.cp_r's ability to copy all contents of the source directory instead of the directory itself. I needed to patch a set of PHP files with a newer subset of those files. The :preserve argument is set to TRUE in the FileUtils.cp_r call so the modification dates of all the files will be usable as a version identifier (otherwise, the modification date becomes "today", which only indicates the date the patch was performed, rather than what version the patch applied was).
129Split a file at delimiting linesAlbert Davidson Chou
This script will split a file at lines identified by a regular expression. The output files will be named using the original file's name with ".1", ".2", etc. appended to the name of each consecutive output file.

I wrote this script because I needed to break up a text file of MySQL table contents dumped out by phpMyAdmin into one big CSV-style file. The delimiting line in this case was the column headings declaration for each table, which started with "ID;".

The command line for this situation was (on OS X):

split_at_line input_file.csv ^\"ID\"

where I had to escape the " characters so they would not be stripped away by bash before it passed the argument to the script.

The script implicitly assumes that its input file is text, not binary, as the format is not specified when opening the files.
131Pulling random elements from an arrayBrian Ewell
Returns a random element from the receiving array, either destructively or non-destructively.
132acts_as_google_accountFidel Santiago
This is a acts_as RoR plugin for validating a username and password against Google.
133Generate and return an array of random numbersSteve Callaway
This is an example of how to generate & return an array of random numbers, of a given length, wihtin a set range. It may or may not generate duplicates. It makes some simplistic assumptions about how to handle 0 length arrays, or issues where the high and low bound are equal etc. which can simply be recoded to fit your needs.

Arguments:
low - low bound of random number
high - high bound of random number
elements - number of elements to populate
134Encode in Adobe Base85 formatRiccardo Bernardini
The function ascii85encode takes an array of bytes or a string and returns a string rappresenting the array in the Adobe Base85 encoding format (see PDF reference manual)
135Roman Numerals
Completely pointless class that converts integers to Roman numerals and vice versa, also extends the integer class with a "to_roman" method. Using method missing as syntactic sugar for converting numerals to numbers.
138load_testerGene Rogers
load_tester is a simple ruby script to stress test a web-server. It uses threads to simulate multiple concurrent connections and is able to authenticate via SSL if a Client Certificate is provided.
153cleanruy jauregui
remove 0 size files from a directory
141aggregate_associationsTobias Habermann
A rails plugin that aims to provide active record with functions to combine two has_many associations together (internally by using "(conditions_1) OR (conditions_2)")
142Extract email address from Yahoo/Gmail email formNasir Khan
Often you copy email addresses from one email program to other. Just now I copied some email addresses from Yahoo to Outlook. One way to do that is to export the address book and import in your favorite email sofwtare.
Sometimes however, you just need to copy without importing. Most of the email programs display emails in the format "John Smith<john.smith@somewhere.com>, Jane Smith<jane.smith@somewhere.com>" and you would like to just extract email address minus all the fluff.
As an example type in some email addresses in your Yahoo compose email form. [These days "Ajax suggest" helps to do it faster than looking through address book], then copy the string and use the script below to extract just the addresses. This is extremely simple.
143uptoChris Peterman
Basically a script to allow use of the upto function outside of Ruby. Written because I needed it in a shell script
154squeezeruy jauregui
This function reads the contents of a file, or a list of files, and prints a non-redundant version; the same files with repeated lines removed.
145Simplest option parserKeith Hodges
When I just want the simplest of command line options this is what I use
146SingleLoggerDov Murik
Singleton logger (instead of global $logger or passing the logger variable to every function).
147Derives FromJames Randall
A handy little script when learning a new library (or Ruby core) that when given the name of a class will tell you all the classes that are derived from it. For example:

ruby derives_from.rb StandardError

Will tell you all the classes that derive from StandardError. Additionally you can specify libraries to load and search. For example the following loads the wxRuby2 library and looks for all derivatives of the Window class:

ruby derives_from.rb Wxruby2::Window wx

The script relies on the fact that class definitions are objects like any other and so end up in the ObjectSpace after a library has been requires.
148Simple JSON parser & builderChihiro Ito
This code snippet contains two simple JSON processing classes. JsonParser converts a JSON string to an array or a hash. JsonBuilder performs vice versa. These classes are standard compliant and are designed for stability and reliability. Especially JsonParser has UTF-8 validation functionality so you can avoid some kind of security attack.

For details, you can generate a document by RDoc.
rdoc SimpleJson.rb
149Nmap Grepable Output ParsingManish Saindane
This script parses the nmap grepable output file and lists the following info for all ips:
Hosts IP
Requested ports(open, filtered or closed)
150Date/Rational/Fixnum#gcd hack increased performance by 15%Kurt Stephens

Date uses Rational heavily, which calls Integer#gcd for every new Rational. The Integer#gcd method is generic to handle Bignums, but performs terribly for Fixnum#gcd(Fixnum), which is probably the most often case.

My RubyInline hack saved 15% execution time in a large Rails application:
152Quadratic Formulapatrick fitzstephens
A quadratic formula script that gets the inputs of the A, B and C numbers and then finds the roots for those numbers.

If you don't know how the quadratic formula works go to: http://www.purplemath.com/modules/quadform.htm
155Simple Web CrawlerScott Nedderman
This is a simple script you can use to crawl a website. It takes a block that is called for each page like so:

sc = SiteCrawler.new(site_url)
@pages = Array.new
sc.crawlSite { |url, page_text|
@pages << url
}


156Array.which_long?Billy Hsu
It will be return the longest item of the array.
157Array.which_long?Billy Hsu
Same as the version 1.
Usage:
puts [1, 12, '123'].which_long?
=> 123
158Service ControlBrian Sanders
Small ruby module which taps into advapi32 to provide an interface to the functions which allow you to start, stop, pause, and query Windows services. I prefer this over using net start/stop.
159Array.longestBilly Hsu
Usage:
[1, 23, 456, '123'].longest
#=> [456, '123']

Better than Array.which_long?
164Matt's Roshambull Rocking Play ScriptMatthew Ford
Lets this script choose what to throw, don't be a predictable fool.
161Load Balancer Member CheckerMichael Behan
Performs HTTP GET requests on an array of hostnames/ips and reports back any failed requests via e-mail. Originally written to check members of a load balanced cluster; can be altered to behave as a general purpose link checker.
162Prime numbersMichael Behan
Extends the Fixnum class with a "primes" method. `100.primes` will return all the prime numbers between 1 and 100.
163Simplified BOFH Excuse GeneratorAnthony Cook
Ported from mexnix's perl script and modified.
Running this code will automatically output a single excuse. This is version .2 because it's bare bones, run the code, and that's it, more changes could/may be made.
165extendible multidimensional array with compact storageJan Wedekind
This is an early version of a class for multidimensional arrays. New element-types and coercions can be added later. Elementwise operations (such as "+" and "-") are very slow at the moment.
166Parse URL parameters into a hashpostmodern
Small method for parsing URL parameters from a URL string into a hash table.
250Kautz graph explorerMarkus Liedl
Script to visualize Kautz graphs using gtk2 and cairo.
252Autotest with iChatPhilip Matarese
An example of a .autotest file that will broadcast your current test state via chat status.

Requires rubyosa and of course ZenTest. Also requires images named rails_ok.png, rails_fail.png, rails_pending.png, and rails_chillin.png.
253Ruby DBF WriterJoe Lobraco
A Ruby function that can write a very basic DBF file.
263Ruby thumbnail generatorStefan Vantroba
Ruby thumbnail generator is simple script which is ideal to use in your Ruby on Rails application to quickly generate thumbnails of any proportions. Just set width and height and get image. It uses GD2 library and stores resized images in the cache to save processing time in next request. Visit: http://www.cleverleap.com/ruby-thumbnail-generator/
for more detail information and installation instructions.
270Broadsoft Ruby Gem ExampleThomas Howe
An example of using the Broadsoft Gem
254Number WangPhilip Matarese
An experiment with Ascii Art and Ruby code.
264Random string generatorGunnar Wolf
Modify the base String class to allow for random strings of any length to be easily generated. This can be useful for generating password salt values, confirmation URLs, or even for generating passwords
255Send Email through QmailAndreas Junizar
Must have qmail-inject in Linux/UNIX.

You will be able to send email through qmail.

Simple!!

This function is only to send email. No other than that.
283minirbTomokiyo Nomura
An ultra short irb-like script. Type ruby expression on the command line to display return value. Type only ';' to enter the multiline input mode. Type only ';' on the command line to exit the multiline input mode. Type 'exit' to exit the program.
316reval.rbpostmodern
Re-evaluates a specified ruby file whenever the file changes. Reval was inspired by Giles Bowkett's kickass talk on Archaeopteryx at RubyFringe 2008, where Giles used some mad shell scripting to re-evaluate a ruby script.

Reval might come in handy, when you give that awesome breakthrough talk at some conference.
256File.each_line (class method for File)Patrik Wenger
Just a quick way for iterating over each line of a given file path. Return value is the number of lines.

Example:
File.each_line("file.txt") do |line|
puts "line = #{line}"
end
273Quick ParseTomokiyo Nomura
A simpe programmable parser. A Lex class object is created with a rex_rule which is an array of [/regexp as a rule/, a character as a type of token, function to applay the value of token] elements. A Parse class object is created with a parse_rule which is an array of [/regexp as a rule/, type of token after reduction, function to apply when match]. A sample program is attached.
284DRuby on RailsKonstantin Haase
Small script for sharing all your models via druby. Note: You should use ACL + SSL or something for security reason.
420count_secondspeter bauer
A small example for using Tk.after to count and display seconds.
267Generic MapperMatt Mitchell
This module will provide 2 methods - map and map!. It allows you to create a set of "rules" that define what single value gets returned from map!. The result depends on the order that the "rules" are defined.
185palindromenaresh cheruku
A word that reads the same in either direction, forward or backward.

For example:- The word MOM is palindrome.
RUN is not
285change MAC addressLex Williams
this script will change the mac address to one you provide.
usage : script.rb <interface> <mac address>
274dial_jajah.rb - make a phone call peter bauer
Make a phone call with the jajah provider from the Command Line. You can also check your balcance and set the number of origin. Jajah already has a web interface but maybe you don't like it or you need to automate your phone calls.
A jajah account (userid and pin) is required.
469deltacloudchad palmer
deltacloud core
195sip_clip.rbpeter bauer
Get the "Caller ID" or CLIP information
out of a SIP VoIP incoming Telephone call.
-Display the "Caller ID" on your TV
equipped with enigma based SAT Reveiver.
Requires a free Ethernet Port on a Linux Box and the possibility to sniff VOIP traffic
(You can use a HUB to "mirror" traffic)
196mynetstat.rbpeter bauer
Small ruby/tk program which tests
if hosts can be reached with the ping.pingecho
method and displays the result in a list with
green "buttons" for reachable hosts.
The network can be scanned with a programmable interval time.
197Jaccard's and Simple Matching CoefficientsDerick Fay
Calculate Jaccard's Coefficient, Simple Matching Coefficients, and Simple Matching Distance for a pair of vectors. Written for clarity.
198math ( SWEDISH )Ale cson
simple sccript to calculate math?
199Class accessorsJared Cooke
Defines a set of macros to create accessor methods for class variables. Operates in the same function as Ruby's instance variable accessors
200Windows rss wallpaper changerBela Babik
first cut, will be updated
257findcsPranay Kanwar
Locates Counter Strike servers on LAN, prints
information such as, IP, map, players, etc.
268Config - DSLMatt Mitchell
A hash configuration generator using a dsl looking syntax.
275PEG parser generator classTomokiyo Nomura
PEG parser gennerator class. The grammar described by PEG will be easily implemented using Peg class. An example program is attached.
4724l4y Converter\x00 null
SMS Language style in indonesia.
286Cross-platform MX lookupJames Schneider
Towards eliminating the need for an outbound SMTP server, this code can find the mail exchanger for the domain specified in an email address.

The code does this by interfacing with the 'nslookup' CLI command which is often available in Windows and UNIX environments.

Ruby can connect directly to this inbound (or target) SMTP server to leave a message for the desired recipient.

Often, this action requires no authentication. Without this capacity, Ruby code must rely on an external relaying mail server that usually requires a mail account and its associated authentication tokens.
258rconcsPranay Kanwar
Rcon ruby console for Counter-Strike Server
administration, with readline support.
287Core Class ExtensionsJames Schneider
All the stuff I've wanted and had to add to Ruby's infrastructure that I've remembered to save.
288English-like password generatornor ton
This code generates English-like (or any language really) passwords based on a dictionary you provide.
278Post Current iTunes Album to TwitterDrew Schimmel
This ruby script will automatically update your Twitter account when you start listening to a new album in iTunes on a Mac. It doesn't send updates for every song, for obvious reasons, and requires the rbosa and twitter4r gems or libraries for ruby. The easiest way to install these on any recent Mac is to open a terminal window and type 'sudo gem install rubyosa' and 'sudo gem install twitter4r'

The script takes two command-line arguments, your Twitter username and password.

So, for example: 'ruby itunes_twitter.rb myusername mypassword'
To run as a background process, simply use 'ruby itunes_twitter.rb myusername mypassword &' instead.
234Database Trickle ArchiverJohn Lauck
Archives a mysql database table in small bite size portions. For example, if your database regularly reaches a 4GB limit and you would like to move two weeks of data to another table (tablename_date) that will simply archive the data; this script handles the process at whatever pace suits your system. It defaults to copying and deleting 10 records every 5 seconds, but is customizable.

Provide the database login info, table name and field name for time stamp comparisons to the script along with a time stamp to begin and end. Other options include the number of records per transaction and time to sleep between transactions.

The script requires the following gems: mysql, cooloptions, log4r and strscan.

I've handled a lot of errors and different cases but please test it before you use it on your live database!

Contributions to the code are very welcome. My top priority is to abstract the fixed time variables so it's possible to easily archive 2 weeks, 1 week or 1 day (etc) prior. This would be extremely helpful since it would make it simple to add cron jobs for schedule d archives. I'm sure there are plenty of other possible extensions. Feel free to tinker.
261WillPaginate - PostFormLinkRendererJames Randall
A link rendered for WillPaginate that allows for the posting of a form and the setting of the page number in a hidden form tag (with the same name as the param_name specified). The form must have an id of form.

It was useful to me as I had two different pages results and a good deal of surrounding form data that needed to be held within a single form.
279Send Multicast dataAlan Davies
Sample ruby code to send multicast data
290dreambox_msgpeter bauer
Send Popup message to Dreambox DM7000 or other enigma based SAT receiver ( Please adjust IP-Address inside script)
>date | dreambox_msg will show a popup with
current date
280Receive multicast dataAlan Davies
Sample code to receive multicast data
470SortedArraySergey Chernov
Array extended to sort elements on tha fly (when inserting) and provides very effective binary search for elements. The rest of Array magick shold work as usual.
248Interactive Alphabetizer-Super SimpleJoe Ganz
This is so simple it shouldn't even be here. Most of you probably already know this if you read Learn to Program by Chris Pine.
You just type in several words, with Enter in between them, and then when you press Enter on a blank line it gives you back the words alphabetized.
Small note on the first line of this snippet: you could also use Array.new, but the Array literals, [], are shorter.
249Method to determine probability of calling a ProcJoe Ganz
Uses the method maybe_do to pass in a Proc, and the probability to call the Proc.
USAGE: In your program, write maybe_do then the Proc you want to call, followed by a comma and the probability that it should happen (integer between 0-100). If you use a negative integer or a number > 100, it will just not do anything.
302Round to closest multiple of...Skye Weir-Mathews
You pass this function a number you want you rounded, and the multiple you want it rounded to and it passes back the rounded number.
343Language Numberszhang bee
Language Numbers
345EnglishNumeralszhang bee
=begin
While we normally write numbers using Arabic (or since Quiz #22,
Roman) numerals, numbers can also be written out as English phrases.

For example:

7 == seven (the hard way)
42 == forty-two (a very important number)
2001 == two thousand and one (a space odyssey)
1999 == (party like it's) nineteen hundred and ninety-nine


So the quiz is a problem from a Pi Mu Epsilon (US national math club)
newsletter:


"When the integers 1 to 10_000_000_000 are written in the English
language, then sorted as strings, which odd number appears first in
the list?"

- Create Ruby code to translate a number to it's English language form.

- Determine programatically which odd number in 1..10_000_000_000
would sort first if written in English. (Brute force is the obvious
solution, but the computer may have to think about it...)

- Would the answer change for a larger range of values, say 10**30?

- Do French and German Rubyists get a different answer than the
Americans?

=end
311Numeros_PalabrasPowerpuff Kuma
Un traducción desde PHP de la paquete Number_Words del proyecto PEAR (http://pear.php.net/package/Numbers_Words) para traducir números y cifras a palabras
336web_command.rbpeter bauer
Simple CGI script which takes a shell command from a html form and executes it. The result is printed below the input form. Could be useful for remote management of a Computer when telnet or ssh login is not possible. The script on its own provides no access control and no user authentication.
346primitive.rb - easy definition of simple classesFabian Streitel
This is primitive.rb, a small function that let's you define a class that is only intended to hold certain attributes with one line of code:
primitive :Klass, [:attr1, :attr2]
in any module.
379Whois
How to implement whois on the most basic level.
471Multiple key Hash getter/setterSergey Chernov
Inpired by python. Allow to access more than one key in the hash in the single index accessor
475RUBY Constant Update (ruby_const_update.rb)Dan Rathbun
Updates older Ruby versions to have constants
like 1.8.7 and 1.9.x, specifically:

RUBY_COPYRIGHT, RUBY_DESCRIPTION and
RUBY_PATCHLEVEL if less than ver 1.8.5-p12
476TextTableJohn Allen
Prints data in a text format in a terminal session. Very useful for displaying debug info or tabular data inside a session. Simply setup the table hash to define column headers and sizes, and then just call a method to print a row of data. It will also multi-line wrap data, or chop depending on the wordwrap option set in the table hash.
More info at http://johnallen.us/?p=347
358Shutdown idle serverTobias Peters
This script runs on a home file server, shutting it down when not in use to save energy, cost, and wear.

The file server runs linux 2.6, and exports files using nfs, samba, sshfs/sftp. The script monitors this activity and shuts down the server when it is no longer in use.
440File AppenderJacob Yates
It will append itself to any ruby file in the current directory, and will not append if they have a CCiC marker.
This Could Be Used For A Bases Of A Simple Appender Virus
445MathExtDick Pountain
Provides a Factorize function and enhances the print formats (to_s method) of Ruby's built-in Complex, Floatand Rational types
450Ruby text editorMichael Lenox
Ruby Editor Program, a basic CLI text editor
478ManageUsersKyle Carter
This class, i.e. ManageUsers, provides termination and provisioning functionality pertaining to active directory.
441File PrependerJacob Yates
Pretty much same as appender, but ofcourse prepends to the file
446SurdsDick Pountain
Adds a new class Surd to Ruby, which permits arithmetic using irrational roots like √2 and √3. Also provides a function to find the roots of a quadratic equation in terms of surds, rather than floats.
373Improved Open StructDavid M
This class provides a few new capabilities in addition to what is provided by the OpenStruct class.

The method _to_hash will return a hash representation of the struct, including nested structs.

The method _table will return a hash representation, but will not resolve any nested structs.

The method _manual_set takes a hash and adds it to the struct. This is similar to OpenStruct's ability to take a hash as an initial argument to create a struct, this method allows the struct to be modifed post instantiation.

The method names start with an _ (underscore) to avoid any conflicts between these methods and struct assignments.

Implementation note: I created a new class rather than extending the existing OpenStruct class due to my personal preference of not changing the behavior for standard library classes. However, one could just as easily extend the OpenStruct class with these behaviors as well.
442File EPO(Entery Point Obscuring)Jacob Yates
It finds a ruby file without the CCiC marker and places code in the middle of host code
454Test sur la sérialisation par YamlJean Tinguely Awais
Un petit script qui test la sérialisation d'objets avec YAML. Il fait aussi appel à la classe test/unit pour obtenir les informations de test
458IP2Location Ruby LibraryHexa How
IP2Location Ruby Library enables the user to find the Country, Region, City, Latitude, Longitude, ZIP code, Time zone, ISP, Domain name, Connection type, Area code and Weather station code of the location that any IP address or hostname originates from. This API is meant to allow easy integration between your program written in Ruby and
the IP2Location Binary (.BIN) data file. It has been optimized for speed and memory utilization. Developers can use the API to query all IP2Location™ binary databases for applications written in C or supporting static/dynamic library. Get more geolocation information at http://www.ip2location.com .
462howtojustin stultz
make awebsite you need to just look at this
482String shuffleruy jauregui
String class extension.
These methods shuffles the characters in a string. If used alone, independent characters are shuffled, if used with arg, sets of arg characters are shuffled.
Depends on Ruby >= 1.9
483.gitignoreAndrew Bell
Sample .gitignore file
484lates snippetCici Wirachmat
Dev which (name)
498How to create executable files in ruby on railsyedukondala reddy
I know the rubyscript2exe, ocra but I don't know the procedure to develop .exe file

Please give the sugessions any one?

Thak you
501BinaryDecimalConverterLars Nielsen
A small script to convert Binary to Decimal and the otherway arround
399life-meterMichael Lenox
A program to determine lifetime as a percentage. It is not very interesting, but it demonstrates ruby's input/output and logic meathods.
402LoginMichael Lenox
Ruby Login Program, a program to play with strings, blocks, and if statements
455Test sur les procs et blocsJean Tinguely Awais
Petit test sur les procs et les blocs avec ruby
409svn conflicts resolverFernando Giannetti
Resolves all the svn conflicts of the file taking allways the newest version as correct.
Requires svn
410MD5 compare with VirustotalRishi Narang
Inputs MD5 from a text file, and validates against the malware hash at Virustotal.
456Test sur les tableauxJean Tinguely Awais
Test sur les arrays et les appels de fonction
523guaguagua gua
http://www.lvshoposnlines.net
524guaguagua gua
http://www.lvshoposnlines.net
561GenLibBob Hostern
A small Ruby file generating class. You must include a file called "makefile.opgenc" in the directory of the snippet in order to work out of the box.
572virtapay2 and RubyCici Wirachmat
Some snippets written by James Toomey in this Ruby-talkposting