Your favorite bit of ruby code?

D

Drew Olson

Carl said:
I'm just curious what your favorite bit of ruby code is? Do you have

The codegolf line for printing the first 34 lines of pascal's triangle:

34.times{k=0;puts ($*.map!{|i|k+k=i}<<1)*" "}

Man, that's succinct.

-Drew
 
D

dblack

Hi --

Hello,

I'm just curious what your favorite bit of ruby code is? Do you have
any small bits, methods, classes, or anything else, that just make you
say "Wow, that is sweet!"

I'd like to see some of them!

I love tons of it but one idiom I've always thought was particularly
striking and expressive is the entry into an object's singleton class:

class << obj

I love the idea that "<< obj" (which I process as something like "from
this object" or "of this object") is enough to satisfy the class
keyword.


David

--
Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black)
(See what readers are saying! http://www.rubypal.com/r4rrevs.pdf)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)
 
M

Marcello Barnaba

Hi,

Hello,

I'm just curious what your favorite bit of ruby code is? Do you have
any small bits, methods, classes, or anything else, that just make you
say "Wow, that is sweet!"
I'd like to see some of them!

require 'irb'

module IRB
def IRB.start_in_binding(b)
setup(nil)
irb = IRB::Irb.new(WorkSpace.new(b))
@CONF[:MAIN_CONTEXT] = irb.context
catch:)IRB_EXIT) { irb.eval_input }
end
end

(taken from http://rubyurl.com/K4P)
 
R

Rodrigo Bermejo

This snippet contains some of my favorite ruby features

class Array
def *(a)
n = Array.new
[ self.length, a.length].max.
times do |x|
n[x] = ( self[x] || 0 ) * ( a[x] || 0 )
end
n
end
end
#[ 2,4,4 ] * [ 5,5 ]




but by far my favorite one liner is:

ruby -r 'fileutils' -e 'FileUtils.rm("/usr/bin/perl")'


-rb.
 
J

James Edward Gray II

This snippet contains some of my favorite ruby features

class Array
def *(a)
n = Array.new
[ self.length, a.length].max.
times do |x|
n[x] = ( self[x] || 0 ) * ( a[x] || 0 )
end
n
end
end
#[ 2,4,4 ] * [ 5,5 ]
[2, 4, 4].zip([5, 5]).map { |l, r| (l || 0) * (r || 0) }
=> [10, 20, 0]
but by far my favorite one liner is:

ruby -r 'fileutils' -e 'FileUtils.rm("/usr/bin/perl")'

That's hilarious!

James Edward Gray II
 
G

Gary Wright

I'm just curious what your favorite bit of ruby code is? Do you have
any small bits, methods, classes, or anything else, that just make you
say "Wow, that is sweet!"

I can't remember where I first saw this bit of code but I was able to
google and find a ruby-talk posting by Wayne Vucenic with:

def quicksort(a)
return a if a.size <= 1
pivot = a[0]
quicksort(a.select {|i| i < pivot }) +
a.select {|i| i == pivot } +
quicksort(a.select {|i| i > pivot })
end

I realize that Ruby has a built in sort but I was absolutely stunned
at how well the quicksort algorithm could be coded in Ruby with
little if any extraneous syntax.

Here is another version that might even be 'better' (via Gabriele Renzi)

def qs(a)
return a if a.size <=1
pivot = a.shift
less, more = a.partition{|y| y < pivot}
qs(less) + [pivot] + qs(more)
end

In ruby 1.9, splat is a little more flexible, which gives:

def qs(a)
return a if a.size <=1
pivot = a.shift
less, more = a.partition{|y| y < pivot}
[*qs(less), pivot, *qs(more)] # only works in 1.9
end

And if you want to use the nice open class features of Ruby:

class Array
def qs
return self if size <=1
pivot = shift
less, more = partition{ |y| y < pivot }
[*less.qs, pivot, *more.qs]
end
end

Gary Wright
 
I

Ilmari Heikkinen

I'm just curious what your favorite bit of ruby code is? Do you have
any small bits, methods, classes, or anything else, that just make you
say "Wow, that is sweet!"

This one's less "Wow" and more ha-ha-ha </robotic laughter>:

class String
def to_proc
eval("lambda{|a|a.#{self}}")
end
end

[1,2,3].map &"*200"
# => [200, 400, 600]
 
D

Daniel DeLorme

Carl said:
I'd like to see some of them!

This is one I particulary like from my personal library. It allows me to do
stuff like:
book.author.ergo.name
instead of:
book.author && book.author.name


require "singleton"
class BlackHole
include Singleton
private
def method_missing(*args); nil; end
for m in public_instance_methods
undef_method(m.to_sym) unless m =~ /^__.*__$/
end
end

class NilClass
def ergo
BlackHole.instance
end
end

class Object
def ergo
if block_given?
yield(self)
else
self
end
end
end
 
B

Bertram Scharpf

Hi,

Am Freitag, 09. Feb 2007, 05:49:25 +0900 schrieb Carl Lerche:
I'm just curious what your favorite bit of ruby code is?

I like a lot the implicit return values.

def subject str
if str =~ /^Subject:\s*/i then
$'
end
end

if (a = subject other) then ...

Bertram
 
B

Brian Candler

require 'irb'

module IRB
def IRB.start_in_binding(b)
setup(nil)
irb = IRB::Irb.new(WorkSpace.new(b))
@CONF[:MAIN_CONTEXT] = irb.context
catch:)IRB_EXIT) { irb.eval_input }
end
end

I've no idea how this works; it has to rate as cool Ruby, even if it isn't
implemented in Ruby :)
http://tryruby.hobix.com/
 
M

Marcello Barnaba

Hi,

require 'irb'

module IRB
def IRB.start_in_binding(b)
setup(nil)
irb = IRB::Irb.new(WorkSpace.new(b))
@CONF[:MAIN_CONTEXT] = irb.context
catch:)IRB_EXIT) { irb.eval_input }
end
end

I've no idea how this works; it has to rate as cool Ruby, even if it isn't
implemented in Ruby :)


3) PREFACE
I understood your sentence as "i've no idea how <the code you pasted>
works..." and started explaining how it works and what can be done with it,
translating the concept being explained in the article I linked in my
previous post (code from the inside out [3]).

In the end, just some picoseconds before hitting "SEND", I realized that you
were referring to tryruby.hobix.com.

I'd feel even dumber if I had thrown away the writeup, maybe it could prove
interesting for someone. I also surely made lots of errors and said lots of
imprecise things. Please correct me. TIA :).



1) WRITEUP
the IRB.start_in_binding method makes you able to start an IRB in whichever
context you want, attaching it to a running ruby program, in the context you
define. let's say, e.g., that you're dissatisfied by using "puts"
or "debugger" to inspect how "things" in your program work, and you'd like to
be *inside* your code, in order to better feel the presence of methods and
objects that you can call and inspect, in some nested place in your code.

e.g. you'd like to write an association extension, but really don't know which
methods can call from that context, or you don't immediately understand in
which scope the association extension code is being called. start_in_binding
to the rescue!

has_many :things do
current_binding = binding # verbose assignment, to make
IRB.start_in_binding(current_binding) # things more clear.
end

when that "has_many" method is run (e.g. by require'ing the model with this
association) another IRB prompt will greet you. welcome inside your program!

with=> Array
and=> true

you can really feel like being an intruder in a foreign land ;), you can try
to call things around, or you can define methods and test them *directly*
into the code. So, the ruby code doesn't go from the source file into the
running instance, it goes exactly the opposite way: you write it inside the
running instance, and if it works you copy it into the source file. Pretty
neat :). The article I linked in my previous post explains this "intruder
pattern", but uses a Tk program as an intrusion point.


if you are unfamiliar with "binding", it is an "execution context", with all
the local variables, methods and 'self' value left in place. Someone can
describe it in more detail than me, or you can just "ri Binding" [1]. You can
pass Binding instances as a second argument to an eval() call, so that the
given code will be evaluated in the passed binding's context.

Kernel#binding returns the current binding.


Some other very neat (hacky?) bit (bunch?) of binding-related code is in
irb/workspace.rb:55

when 3 # binging in function on TOPLEVEL_BINDING(default)
@binding = eval("def irb_binding; binding; end; irb_binding",
TOPLEVEL_BINDING,
__FILE__,
__LINE__ - 3)

here it is defined a method that returns ITS binding, and then it is being
called. that method is executed in TOPLEVEL_BINDING context, and its return
value (a "clean" binding inside Object#irb_binding) is stored in @binding.
@binding is used for further evaluation. that's schweet :).


other options, always in workspace.rb:

when 0 # binding in proc on TOPLEVEL_BINDING
@binding = eval("proc{binding}.call",
TOPLEVEL_BINDING,
__FILE__,
__LINE__)


here the binding is pulled out from an anonymous lambda call..



the most hacky, imho:

when 1 # binding in loaded file
require "tempfile"
f = Tempfile.open("irb-binding")
f.print <<EOF
$binding = binding
EOF
f.close
load f.path
@binding = $binding

write-some-temp-file-that-stores-the-binding-in-a-global-var-and-pull-out-that-one-using-load

!


sorry for this long blob of things that experienced ruby users know like their
hands, but I went through this stuff some time ago, and while I was
understanding how it works, i learnt all the Binding stuff [2]. it was like
being in a journey through different execution worlds ;) and I had lot of fun
putting all the pieces together. And I'm sharing my fun and my horrid
english ;).

Marcello




2) FOOTNOTES
[1]: i suggest <http://eigenclass.org/hiki.rb?fastri> if you feel that ri is
too (fscking) slow in doing its job.

[2]: the next step were eigenclasses, which I understood completely only after
reading the RHG <http://rhg.rubyforge.org>. even that was fun. ruby's magic
dust.. :)

[3]: http://rubyurl.com/K4P
 
J

John Carter

That's a very nice little demo of Ruby's charm, John.

I truly wish I could claim it was Mine....

But alack, it is shamelessly copied off a post here on Ruby talk a
year or two back...

In my defense I can say at least I truly listened and remembered when
the master spoke... even if I forgot to remember the Masters name. :)



John Carter Phone : (64)(3) 358 6639
Tait Electronics Fax : (64)(3) 359 4632
PO Box 1645 Christchurch Email : (e-mail address removed)
New Zealand
 

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,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top