ANN: Ruby Underscore 0.1.0 Released

D

Daniel Ribeiro

= RubyUnderscore
*Simple way to create simple blocks*

Ruby Underscore repository:
https://github.com/danielribeiro/RubyUnderscore

Closures are very useful tools, and ruby Enumerable mixin makes them
even more useful.

However, as you decompose more and more your iterations into a sequence
of maps, selects, rejects, group_bys and reduces, more commonly you see
simple blocks such as:

collection.map { |x| x.invoke }
dates.select { |d| d.greater_than(old_date) }
classes.reject { |c| c.subclasses.include?(Array) }

RubyUnderscore modify classes so that you can also use a short notation
for simple closures. With such, the above examples can be written as:

collection.map _.invoke
dates.select _.greater_than old_date
classes.reject _.subclasses.include? Array

Just replace the iterating argument with the underscore symbol (_), and
ditch the parenthesis.

= Quick Example

The example consists of getting all instance methods of String, Array,
Class that end with 'd?'

require 'ruby_underscore'

class MethodFinder
include RubyUnderscore::Base

def find_interrogation_methods
[String, Array, Class].map(_.public_instance_methods.grep
/d\?$/).flatten.sort.uniq
end
end
p MethodFinder.new.find_interrogation_methods

= Using Ruby Underscore

As in the example above, simply by including the module include
RubyUnderscore::Base on the class, all methods (class methods as well)
will allow you to use the underscore symbol to write simple blocks.
 
J

John Mair

Why not just use Symbol#to_proc ?

So

collection.map _.invoke

becomes:

collection.map &:invoke
 
D

Daniel Ribeiro

Doesn't work when you need to chain more than one method or even pass
argument:

dates.select _.greater_than old_date
(dates.select &:"greater_than #{old_date}" not only doesn't work, but if
did, it would take the current value of old_date, not the one you'd get
when you evaluate the block)

But for the very most simple examples, you are right.

John Mair wrote in post #959875:
 
D

Daniel Ribeiro

John Mair wrote in post #960016:
ah, youre right :) nice program btw, very cool!

Thanks. Btw, I forgot to mention: doesn't work on 1.9, as parse tree is
broken on it. Next releases will probably take Roger's suggestions
(http://metaphysicaldeveloper.wordpr...e-a-bit-of-arc-and-scala-in-ruby/#comment-148
and
http://metaphysicaldeveloper.wordpress.com/2010/03/31/improving-ruby/#comment-122),
and see if we can unify it as well (he mentioned that proc#to_string was
being considered to be implemented).
 

Ask a Question

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

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

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,699
Latest member
AnneRosen

Latest Threads

Top