Sam Stephenson <sstephenson / gmail.com> writes:

> There's a few trivial but useful "extensions" to Ruby's standard
> library that I find myself using in most of my projects. I'll share a
> couple, and I'd really love to see what you're using, too.
>
> [...]
>
> Please share your quickies!

These threads make the util.rb files from my long-abandoned projects
feel useful again.

Here's my take on Lisp's PROG1:

|  def before_returning (value, &action)
|    action.call
|    return value
|  end

And an example:

| class IdSupply
|   def initialize
|     @id = 0
|   end
| 
|   def next
|     before_returning @id do
|       @id += 1
|     end
|   end
| end

Here's a convenient abstraction of some uses of Array#each:

| def each_call (id, things)
|   things.each do |thing|
|     self.send id, thing
|   end
| end

And an example:

| things = [1, 2, 3, 4, 5, 6, 7, 8]
| unwanted = [3, 6, 2, 1, 5]
| things.each_call :delete, unwanted

Here's my take on prototype-based programming:

| def add_method (id, &closure)
|   (class << self; self; end).send(:define_method, id, &closure)
| end

And an example:

| foo = [1, 2, 3]
| foo.add_method :frob do |x|
|   self[x] * self.length
| end
| 
| # foo.frob 1 => 6

Here's some shuffling stuff:

| class Array
|   def shuffle!
|     each_index do |j|
|       i = rand(size - j)
|       self[j], self[j+i] = self[j+i], self[j]
|     end
|     self
|   end
|   
|   def shuffle
|     self.clone.shuffle!
|   end
| end 

And that's it.

  mikael