| Snippet ID |
Title |
|
 |
| Packages Of Snippets | | 2 | hatenabm | drawnboy |
| Hatena Bookmark AtomAPI binding for Ruby. |
| 3 | libvalidtypes | babu proof |
| User Input Validation Framework |
| 4 | rubypkg | Jayen Chandra |
| rubypkg |
| 5 | File Splitter and Joiner | Saajan 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 |
| 36 | motally | Motally Inc. |
| motally tracker for websites, easy to integrate |
| 8 | AjaxTree | sur max |
| Sample Rails application for Ajax based drag drop tree. |
| 22 | Rails PG Procedures | Scott Noel-Hemming |
| Used to create Stored Procedures and adding Trigger Functions to tables in a PostgreSQL database in Rails. |
| 28 | Useful Ruby Extensions | James Schneider |
| Various extensions to core and standard libraries. |
| 32 | Remove Strip | Amit Agarwal |
| To remove strip in column from the model |
| 33 | Language Numbers | zhang bee |
| Some kinds of Numbers are in English! |
| 38 | Surd arithmetic | Dick Pountain |
| Permits arithmetic using irrational roots in symbolic form, like √2 or 3+√5 from a Ruby program. |
| 39 | Surd arithmetic | Dick Pountain |
| Let's you return values including irrational roots like √2 or 3+√5 from a Ruby program, by defining a class Surd. |
| 40 | justin | justin stultz |
| it will be about me and my life |
| 41 | nike shoes | justin stultz |
| all about shoes |
| 45 | 2008 | ming xu |
| 981321 |
| 46 | Simple code | Serheo Shatunov |
| Simple rails code. designless to-do list. |
| 50 | MS word document manipulation | Cici Wirachmat |
| Some snippets written by James Toomey in this ruby-talkposting: http:blade.nagaokaut.ac.jp/cgi-bin/scat-rb/ruby/ruby-talk/60004 |
| 51 | RubySnips | Larry Kite |
| Snippets of Ruby |
| 52 | virtapay | Cici Wirachmat |
| Business Website using Ruby on Rails |
| 57 | Free Microsoft Points Codes 2012 Release | Betty Green |
| http://getfreemicrosoftpointscodes2011.blogspot.com/2012/02/free-microsoft-points-codes-2012.html |
| 75 | Well_Being | Jyoti Kakarala |
| Well Being |
| 76 | laplace | Wictor Borisov |
| Laplace transform inverse |
| 77 | laplace | Wictor Borisov |
| Laplace transform inverse |
| 78 | laplace | Wictor Borisov |
| Laplace transform inverse |
| Snippets |
| 1 | hash to struct | Daniel Berger |
| A method to convert a Hash into a Struct |
| 2 | Deep Copy | Matthew 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!) |
| 3 | Fuzzy Match | Matthew Linnell |
| A (rough) fuzzy match mechanism for strings. Returns 0 <= score <= 1. |
| 6 | Parse one XML element from a file | Tom Copeland |
| Parses one XML element out of a given file |
| 5 | linecat | David Dembinski |
| Two ways to read stdin one line at a time, concatenate the results, strip the newlines, and return the results to stdout. |
| 7 | MS Word document manipulation | Tom 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
|
| 8 | Commify a number | Tom 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. |
| 9 | DS3C3 | David Dembinski |
| Discordian Society Super Secret Cryptographic Cypher Code |
| 17 | Worlds simplest SQL Server (or MSDE) query code | Ralph 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) |
| 11 | Randomizing an Array | Florian Groß |
| Randomizes the elements of an Array. |
| 12 | Observable attribute | Jim 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(). |
| 13 | Windows Registry | Rodrigo Bermejo |
Check if a given software is installed on the local machine.
For more information about Registry manipulation look at 'win32/registry.rb'
|
| 15 | Names | Charles Hixson |
A quite simple hash lookup that is used with sparsearray.
(re: formatting. It looks best with 3 spaces for tabs) |
| 16 | multi-dimensioned sparse array | Charles 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.
|
| 19 | Win32::Print | David Naseby |
| A wrapper around the Win32 Print related functions. |
| 20 | [ 2 , 4 ] * [ 5, 5 ] | Rodrigo Bermejo |
| Array multiplication |
| 22 | Why 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.
|
| 25 | SuperStruct | Hal 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. |
| 26 | Clear/delete all Internet Explorer cache files | Zoran 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 |
| 30 | Small talk like if branches | Logan 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." }
|
| 31 | Persistant IRB Command History | Michael 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.
|
| 29 | Second simplest json parser in the universe | Ralph 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 => |
| 32 | cmdwatch - repeat a command in a curses window | Steven 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'. |
| 33 | Convert MD5 hash from Hex to Base64 encoding | Andres Andreu |
| This function takes a hex encoded MD5 hash and converts it to a base64 encoded representation. |
| 35 | grace - 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. |
| 36 | Database backup | Matthew 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. |
| 37 | Generic #== method | Zakaria 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 |
| 39 | BatchFileEditor | James McCarthy |
Great IO example,
(IMHO)
Replaces simple characters with other ones in files of type specified
Meant for *nix.
My first working Ruby code.
|
| 40 | New PostgreSQL database & tables through Ruby | James McCarthy |
Creating a database in postgreSQL through Ruby
and creating tables within that database |
| 41 | Simple date manipulation examples | James McCarthy |
Howto use & manipulate dates in Ruby.
|
| 44 | struct to hash | Kevin Howe |
| A method to convert a Struct into a Hash |
| 45 | IRB as a shell | Logan Capaldo |
This goofy thing lets you use irb as a shell, of sorts
Usage:
irb(main):001:0> ls "-l", "--color=auto"
|
| 46 | rapt - Debian Apt wrapper script | Alan Chen |
| A ruby frontend combining many commonly used apt/dpkg commands into one command-line script |
| 47 | Mispel | John 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
|
| 48 | Mail List HTTP Link Extractor/Uploader | Timothy 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. |
| 49 | Web Site Indexer/Uploader | Timothy 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. |
| 50 | Diff Mode Web Site Updater | Timothy 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. |
| 51 | Array[Array] & Array.slice(Array) std-lib extension | Jannis 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] |
| 54 | Binary Search | Ernest Ellingson |
| Performs a binary search on a Ruby array. It does this by adding a function find to the Array class |
| 57 | latexnotes | Logan 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. |
| 56 | Wrapper Class for WM_SETTINGCHANGE | Steve 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. |
| 58 | Filenames to 7-bit ASCII | Kaspar 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 |
| 59 | Duplicate a file | Devin Bayer |
| will duplicate original file number times |
| 60 | ruby which | Bruno Carnazzi |
| which command ruby equivalent |
| 61 | Processing an array of regexps | Steve 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. |
| 62 | XBase/DBase Reader class | Lyndon Samson |
| A class to allow access to DBase DBF files. |
| 63 | Ring Menu System | Vince Marra |
| This is a custom ring menu system, by LoneWolf, for the RMXP. |
| 64 | Ring Menu System | Vince Marra |
| This is a custom ring menu system, by LoneWolf, for the RMXP. |
| 65 | Ring Menu System | Vince Marra |
| This is a custom ring menu system, by LoneWolf, for the RMXP. |
| 66 | Ring Menu System | Vince Marra |
| This is a custom ring menu system, by LoneWolf, for the RMXP. |
| 67 | Lists methods of objects in IRB | Assaph Mehr |
Gives a quick list of an objects methods.
Useful in IRB and breakpoint. Just put this in your ~/.irbrc |
| 68 | dynamic hash-tree | Harro L |
| This component stores objects in a tree structure, creating nodes automatically when needed. |
| 69 | objdump wrapper | jason 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.
|
| 70 | MemoryProfile.rb | John 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 |
| 71 | Expand environment variables | Stefan 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. |
| 75 | cdrpgsql.cgi | Balwinder S Dheeman |
| To view Asterisk's call detail records from PGSQL database via web. |
| 78 | RingBuffer | Dirk 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.
|
| 79 | WinGrep | Dirk 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> |
| 80 | mini 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!
|
| 76 | cdrfile.cgi | Balwinder S Dheeman |
To view Asterisk's call detail records from CSV file via web.
|
| 77 | config.rb | Balwinder S Dheeman |
| Class to read/write config files with [sections], keywords = value pairs. |
| 81 | CoReturn | Scott Bronson |
| If a function returns via coreturn, execution resumes at the coreturn statement rather than starting over at the top. |
| 82 | PriorityQueue | Joel VanderWerf |
Maintain a threadsafe priority queue. Priority is assigned when pushing. Pop removes the highest priority element.
Requires rbqueue. Includes test. |
| 83 | Debian Package Explorer | Richard 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.
|
| 85 | filesystem recursive deletion | Gary 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! |
| 86 | long argument list parser | ruy 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.
|
| 87 | File Recursive | Felix Sun |
| To get every file in the given folder include subfolder. |
| 88 | MyVars | Devin Mullins |
| Prints local, instance, and class variables. Useful in an irb or ruby/breakpoint debugging session. |
| 89 | Range Sum | Robert Myers |
| function that returns the sum of every number within a range, without the use of looping. |
| 91 | Convert colon separated time to seconds | Michael 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. |
| 92 | Primes / Factoring | Justin 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. |
| 93 | Instant Intent | Chiaro 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
}
|
| 94 | RUDL :undefined function fixed | olamide bakre |
| This fix the problem with RUDL.so when it looks for the print_centered function, it will not crash |
| 95 | Duplicate PHP's print_r function | Kevin Baird |
| Adds a print_r method to Object. Useful for debugging. Reconfigures itself for either Ruby1.6 or 1.8 as needed. |
| 97 | WeBrick with .rhtml Files | Friedrich 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. |
| 99 | Ruby code to fill in unmatched braces | Kaushik 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. |
| 102 | mkfavorities | Balwinder S Dheeman |
Create a Favorities tree for IE from your Firefox's bookmarks.html file.
|
| 101 | Tiny Encryption Algorithm | Jeremy Hinegardner |
This is a pure ruby implementation of the Tiny Encryption Algorithm (TEA) by David Wheeler and Roger Needham of the Cambridge Computer
Laboratory. |
| 103 | Ruby Chat Server | Christopher 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. |
| 104 | Commify a Number | Craig 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"
|
| 105 | File Splitter | Saajan N |
File Splitter: Split a file into a number of smaller pieces
|
| 106 | File Joiner | Saajan N |
| File Joiner: Join all your "piece" files into a single file again |
| 107 | convert time in seconds to uptime | Erik 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.
|
| 108 | String XOR | Dag 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. |
| 109 | QuickSort | Steve Shuer |
| a pure ruby quicksort implementation |
| 110 | Create package for release on rubyforge | Soemirno Kartosoewito |
| Creates packages from a tag in the sourcetree. |
| 113 | Simple Actions for Rails Controllers | Christian Romney |
| DRY up controllers by metaprogramming empty action definitions to preserve the ability to use layouts. |
| 112 | SHOUTcast Stream Saver | Leonardo Guilherme de Freitas |
Save streams of shoutcast radios with song title.
Songs will be saved in the script directory. |
| 114 | assert_change/assert_no_change | Matthew Abonyi |
| Asserts that what is returned by an object's method has or has not changed. Inspired by assert_difference/assert_no_difference. |
| 116 | Simple Encryption | David 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. |
| 117 | WEBrick Reverse Proxy Server | Richard 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. |
| 120 | SRK/T calculation | Luke 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! |
| 121 | Ruby as a shell: take 2 | Jordan Callicoat |
| A little experiment inspired by snippet #45. Just a proof-of-concept really. |
| 123 | KELKO::DATA::Tree | kelko |
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 |
| 124 | KELKO::DATA::BstarTree | kelko |
| an implementation of a so-called B*-Tree |
| 125 | KELKO::DATA::Buffer | kelko |
| a small buffer |
| 126 | KELKO::TOOLS::PWgen | kelko |
| a generator for random 'passwords' |
| 127 | KELKO::DATA::Queue | kelko |
| a simple queue implemented using an array |
| 128 | FileUtils.cp_r wrapper for patching a tree of files | Albert 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). |
| 129 | Split a file at delimiting lines | Albert 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. |
| 131 | Pulling random elements from an array | Brian Ewell |
| Returns a random element from the receiving array, either destructively or non-destructively. |
| 132 | acts_as_google_account | Fidel Santiago |
| This is a acts_as RoR plugin for validating a username and password against Google. |
| 133 | Generate and return an array of random numbers | Steve 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
|
| 134 | Encode in Adobe Base85 format | Riccardo 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) |
| 135 | Roman 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. |
| 138 | load_tester | Gene 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. |
| 153 | clean | ruy jauregui |
| remove 0 size files from a directory |
| 141 | aggregate_associations | Tobias 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)") |
| 142 | Extract email address from Yahoo/Gmail email form | Nasir 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. |
| 143 | upto | Chris Peterman |
| Basically a script to allow use of the upto function outside of Ruby. Written because I needed it in a shell script |
| 154 | squeeze | ruy 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.
|
| 145 | Simplest option parser | Keith Hodges |
| When I just want the simplest of command line options this is what I use |
| 146 | SingleLogger | Dov Murik |
| Singleton logger (instead of global $logger or passing the logger variable to every function). |
| 147 | Derives From | James 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. |
| 148 | Simple JSON parser & builder | Chihiro 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
|
| 149 | Nmap Grepable Output Parsing | Manish 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)
|
| 150 | Date/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:
|
| 152 | Quadratic Formula | patrick 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 |
| 155 | Simple Web Crawler | Scott 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
}
|
| 156 | Array.which_long? | Billy Hsu |
| It will be return the longest item of the array. |
| 157 | Array.which_long? | Billy Hsu |
Same as the version 1.
Usage:
puts [1, 12, '123'].which_long?
=> 123 |
| 158 | Service Control | Brian 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. |
| 159 | Array.longest | Billy Hsu |
Usage:
[1, 23, 456, '123'].longest
#=> [456, '123']
Better than Array.which_long? |
| 164 | Matt's Roshambull Rocking Play Script | Matthew Ford |
| Lets this script choose what to throw, don't be a predictable fool. |
| 161 | Load Balancer Member Checker | Michael 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. |
| 162 | Prime numbers | Michael Behan |
| Extends the Fixnum class with a "primes" method. `100.primes` will return all the prime numbers between 1 and 100. |
| 163 | Simplified BOFH Excuse Generator | Anthony 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. |
| 165 | extendible multidimensional array with compact storage | Jan 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. |
| 166 | Parse URL parameters into a hash | postmodern |
| Small method for parsing URL parameters from a URL string into a hash table. |
| 250 | Kautz graph explorer | Markus Liedl |
| Script to visualize Kautz graphs using gtk2 and cairo. |
| 252 | Autotest with iChat | Philip 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. |
| 253 | Ruby DBF Writer | Joe Lobraco |
| A Ruby function that can write a very basic DBF file. |
| 263 | Ruby thumbnail generator | Stefan 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. |
| 270 | Broadsoft Ruby Gem Example | Thomas Howe |
| An example of using the Broadsoft Gem |
| 254 | Number Wang | Philip Matarese |
| An experiment with Ascii Art and Ruby code. |
| 264 | Random string generator | Gunnar 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 |
| 255 | Send Email through Qmail | Andreas 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. |
| 283 | minirb | Tomokiyo 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. |
| 316 | reval.rb | postmodern |
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. |
| 256 | File.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 |
| 273 | Quick Parse | Tomokiyo 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. |
| 284 | DRuby on Rails | Konstantin Haase |
| Small script for sharing all your models via druby. Note: You should use ACL + SSL or something for security reason. |
| 420 | count_seconds | peter bauer |
| A small example for using Tk.after to count and display seconds. |
| 267 | Generic Mapper | Matt 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. |
| 185 | palindrome | naresh cheruku |
A word that reads the same in either direction, forward or backward.
For example:- The word MOM is palindrome.
RUN is not |
| 285 | change MAC address | Lex Williams |
this script will change the mac address to one you provide.
usage : script.rb <interface> <mac address> |
| 274 | dial_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. |
| 469 | deltacloud | chad palmer |
| deltacloud core |
| 195 | sip_clip.rb | peter 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) |
| 196 | mynetstat.rb | peter 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. |
| 197 | Jaccard's and Simple Matching Coefficients | Derick Fay |
| Calculate Jaccard's Coefficient, Simple Matching Coefficients, and Simple Matching Distance for a pair of vectors. Written for clarity. |
| 198 | math ( SWEDISH ) | Ale cson |
| simple sccript to calculate math? |
| 199 | Class accessors | Jared Cooke |
| Defines a set of macros to create accessor methods for class variables. Operates in the same function as Ruby's instance variable accessors |
| 200 | Windows rss wallpaper changer | Bela Babik |
| first cut, will be updated |
| 257 | findcs | Pranay Kanwar |
Locates Counter Strike servers on LAN, prints
information such as, IP, map, players, etc.
|
| 268 | Config - DSL | Matt Mitchell |
| A hash configuration generator using a dsl looking syntax. |
| 275 | PEG parser generator class | Tomokiyo Nomura |
| PEG parser gennerator class. The grammar described by PEG will be easily implemented using Peg class. An example program is attached. |
| 472 | 4l4y Converter | \x00 null |
| SMS Language style in indonesia. |
| 286 | Cross-platform MX lookup | James 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. |
| 258 | rconcs | Pranay Kanwar |
Rcon ruby console for Counter-Strike Server
administration, with readline support. |
| 287 | Core Class Extensions | James Schneider |
| All the stuff I've wanted and had to add to Ruby's infrastructure that I've remembered to save. |
| 288 | English-like password generator | nor ton |
| This code generates English-like (or any language really) passwords based on a dictionary you provide. |
| 278 | Post Current iTunes Album to Twitter | Drew 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. |
| 234 | Database Trickle Archiver | John 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. |
| 261 | WillPaginate - PostFormLinkRenderer | James 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. |
| 279 | Send Multicast data | Alan Davies |
| Sample ruby code to send multicast data |
| 290 | dreambox_msg | peter 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
|
| 280 | Receive multicast data | Alan Davies |
| Sample code to receive multicast data |
| 470 | SortedArray | Sergey 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. |
| 248 | Interactive Alphabetizer-Super Simple | Joe 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. |
| 249 | Method to determine probability of calling a Proc | Joe 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. |
| 302 | Round 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. |
| 343 | Language Numbers | zhang bee |
| Language Numbers |
| 345 | EnglishNumerals | zhang 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 |
| 311 | Numeros_Palabras | Powerpuff 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 |
| 336 | web_command.rb | peter 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. |
| 346 | primitive.rb - easy definition of simple classes | Fabian 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. |
| 379 | Whois | |
| How to implement whois on the most basic level. |
| 471 | Multiple key Hash getter/setter | Sergey Chernov |
| Inpired by python. Allow to access more than one key in the hash in the single index accessor |
| 475 | RUBY 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 |
| 476 | TextTable | John 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 |
| 358 | Shutdown idle server | Tobias 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. |
| 440 | File Appender | Jacob 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 |
| 445 | MathExt | Dick Pountain |
| Provides a Factorize function and enhances the print formats (to_s method) of Ruby's built-in Complex, Floatand Rational types |
| 450 | Ruby text editor | Michael Lenox |
| Ruby Editor Program, a basic CLI text editor |
| 478 | ManageUsers | Kyle Carter |
| This class, i.e. ManageUsers, provides termination and provisioning functionality pertaining to active directory. |
| 441 | File Prepender | Jacob Yates |
| Pretty much same as appender, but ofcourse prepends to the file |
| 446 | Surds | Dick 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. |
| 373 | Improved Open Struct | David 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. |
| 442 | File EPO(Entery Point Obscuring) | Jacob Yates |
| It finds a ruby file without the CCiC marker and places code in the middle of host code |
| 454 | Test sur la sérialisation par Yaml | Jean 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 |
| 458 | IP2Location Ruby Library | Hexa 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 . |
| 462 | howto | justin stultz |
| make awebsite you need to just look at this |
| 482 | String shuffle | ruy 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 | .gitignore | Andrew Bell |
| Sample .gitignore file |
| 484 | lates snippet | Cici Wirachmat |
| Dev which (name) |
| 498 | How to create executable files in ruby on rails | yedukondala 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 |
| 501 | BinaryDecimalConverter | Lars Nielsen |
| A small script to convert Binary to Decimal and the otherway arround |
| 399 | life-meter | Michael Lenox |
| A program to determine lifetime as a percentage. It is not very interesting, but it demonstrates ruby's input/output and logic meathods. |
| 402 | Login | Michael Lenox |
| Ruby Login Program, a program to play with strings, blocks, and if statements |
| 455 | Test sur les procs et blocs | Jean Tinguely Awais |
| Petit test sur les procs et les blocs avec ruby |
| 409 | svn conflicts resolver | Fernando Giannetti |
Resolves all the svn conflicts of the file taking allways the newest version as correct.
Requires svn |
| 410 | MD5 compare with Virustotal | Rishi Narang |
| Inputs MD5 from a text file, and validates against the malware hash at Virustotal. |
| 456 | Test sur les tableaux | Jean Tinguely Awais |
| Test sur les arrays et les appels de fonction |
| 523 | guagua | gua gua |
| http://www.lvshoposnlines.net |
| 524 | guagua | gua gua |
| http://www.lvshoposnlines.net |
| 561 | GenLib | Bob 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. |
| 572 | virtapay2 and Ruby | Cici Wirachmat |
| Some snippets written by James Toomey in this Ruby-talkposting |