Your favorite bit of ruby code?

On 2/9/07, Pit C. [email protected] wrote:

Thanks for the picture and the interesting read. In return, here’s a
“F” => “”,
“Y” => “+FX–FY+”,
“X” => “-FX++FY-”,
}

Ah! I knew (and was secretly hoping) that would happen. :stuck_out_tongue:

And that is one of my favorite parts about Ruby.

Highest Regards,
-Harold

On Feb 9, 5:39 am, “Erik V.” [email protected] wrote:

In general, AFAIK, an initialize can be skipped if all it does
is a super with the same arguments.

What am I missing? I want to learn… ;]

Oh right. Yes, it can be removed in this case. I incidently left it b/
c the full version of Functor also stores the function and allows for
passthru args. Ie.

class Functor < Proc

private *instance_methods.select { |m| m !~ /(^__|^\W|^binding

$)/ }

def initialize(*arguments, &function)
  @arguments = arguments
  @function = function
  super(&function)
end

def method_missing(op, *args, &blk)
  call(op, *(@arguments + args), &blk)
end

def to_a ; @arguments ; end
def to_proc ; @function ; end

end

Passthru arguments aren’t strictly neccessary in Ruby b/c of closures,
but they are proper. BTW I’ve never been sure what to call the #to_a
and #to_proc methods, those are the best reader method names I’ve come
up with. But then again maybe full accessors would desriable. In any
case they are simply extra features, and not germane to the core
defintion, which is why I left them out of “my favorite bit of ruby”.

Make sense?
T.

Carl L. wrote:

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

Hi –

On Fri, 9 Feb 2007, Carl L. wrote:

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

Hi,

On Thursday 08 February 2007 21:49, Carl L. wrote:

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)

On Feb 9, 2007, at 6:01 PM, Rodrigo B. wrote:

   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 G. 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 ]

but by far my favorite one liner is:

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

-rb.

On Feb 8, 2007, at 3:49 PM, Carl L. wrote:

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 V. 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 W.

On 2/8/07, Carl L. [email protected] wrote:

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]

Carl L. wrote:

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

On Sat, Feb 10, 2007 at 08:10:52AM +0900, Marcello B. wrote:

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 :slight_smile:
http://tryruby.hobix.com/

Hi,

Am Freitag, 09. Feb 2007, 05:49:25 +0900 schrieb Carl L.:

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

On Feb 9, 2007, at 16:01, Rodrigo B. wrote:

but by far my favorite one liner is:

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

ruby -run -e rm /usr/bin/perl

On Fri, 9 Feb 2007, Luciano R. wrote:

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. :slight_smile:

720
John C. Phone : (64)(3) 358 6639
Tait Electronics Fax : (64)(3) 359 4632
PO Box 1645 Christchurch Email : [email protected]
New Zealand

Hi,

On Saturday 10 February 2007 15:07, Brian C. wrote:

end

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

  1. PREFACE
    I understood your sentence as “i’ve no idea how
    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

self.class
=> Array
and
self.class.ancestors.include? AssociationProxy
=> 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 :wink: and I had lot
of fun
putting all the pieces together. And I’m sharing my fun and my horrid
english ;).

Marcello

  1. 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… :slight_smile:

On 2/10/07, Eric H. [email protected] wrote:

On Feb 9, 2007, at 16:01, Rodrigo B. wrote:

but by far my favorite one liner is:

ruby -r ‘fileutils’ -e ‘FileUtils.rm(“/usr/bin/perl”)’

ruby -run -e rm /usr/bin/perl

I am just wondering, is it not rather Python we should fear.
I just recently needed a telnet tool fast on a customer machine with
Python
and without Ruby.
I got the job down, but what a pain!!!
That of course is because I know Ruby and I do not know Python, I
respect
Python, I just prefer Ruby and
I fear Python… especially here in France
BTW the threading lib of Python is awesome but I had to put
parenthesis
and write str(x) …

Just my micromoney
Robert

On 2/10/07, John C. [email protected] wrote:

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. :slight_smile:

It was me(1) who said: “When stealing, steal only from the best” :wink:

Stolen from Faulkner if I recall correctly.
Robert