Forum: Ruby Your favorite bit of ruby code?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
7eb8dd853f87b15352a3b86d37f48ec6?d=identicon&s=25 Carl Lerche (Guest)
on 2007-02-08 21:50
(Received via mailing list)
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!

thanks,
-carl
A131b672fdbd2a58dce12031ad78b121?d=identicon&s=25 Wolfgang Nádasi-Donner (wonado)
on 2007-02-08 22:06
(Received via mailing list)
Carl Lerche schrieb:
> I'm just curious what your favorite bit of ruby code is?

Well, in german ruby forum I use since longer time as part of my
signature

def a(&a);yield(a,10);end;a{|a,i|(i==1)?(print "los gehts!\n"):(print
"#{i-=1}...";a.call(a,i))}

which produces

9...8...7...6...5...4...3...2...1...los gehts!

Pretty useless.

Wolfgang Nádasi-Donner
D812408537ac3a0fa2fec96eb8811559?d=identicon&s=25 John Carter (johncarter)
on 2007-02-08 22:37
(Received via mailing list)
On Fri, 9 Feb 2007, Carl Lerche 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!"

# Ruby is Objects all the way down and open for extension...

class Integer
   def factorial
     return 1 if self <= 1
     self * (self-1).factorial
   end
end

6.factorial
720




John Carter                             Phone : (64)(3) 358 6639
Tait Electronics                        Fax   : (64)(3) 359 4632
PO Box 1645 Christchurch                Email : john.carter@tait.co.nz
New Zealand
83ca41657a99b65d99889abe712ba5e2?d=identicon&s=25 Jason Roelofs (Guest)
on 2007-02-08 22:46
(Received via mailing list)
Can't say I've used this bit of code anywhere, but it's the same feature
as
John's post, with a twist:

class NilClass
  def to_s
    "Hi! My name is Nil! You can call me Nil!"
  end
end

puts nil.to_s  #=> "Hi! My name is Nil! You can call me Nil!"

I love ruby!

Jason
D812408537ac3a0fa2fec96eb8811559?d=identicon&s=25 John Carter (johncarter)
on 2007-02-08 22:47
(Received via mailing list)
On Fri, 9 Feb 2007, Carl Lerche 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!"

It's the  IO.read().scan(%r{}mx){|m| ...} paradigm here I love...

Equally Good is `command`.scan(%r{}mx){|m| ...}

ruby -e 'IO.read("ruby/eval.c").scan(%r{^([a-z_]+)\s*\(.*?\{}m){|m|puts
$1}'
rb_jump_context
rb_secure
rb_secure_update
rb_check_safe_obj
rb_check_safe_str
raise_undef
rb_clear_cache
rb_clear_cache_for_remove
rb_clear_cache_by_id
rb_clear_cache_by_class




John Carter                             Phone : (64)(3) 358 6639
Tait Electronics                        Fax   : (64)(3) 359 4632
PO Box 1645 Christchurch                Email : john.carter@tait.co.nz
New Zealand
D812408537ac3a0fa2fec96eb8811559?d=identicon&s=25 John Carter (johncarter)
on 2007-02-08 22:55
(Received via mailing list)
On Fri, 9 Feb 2007, Carl Lerche 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!"

Ok, I have run out of time to list them all in detail...

But things involving
   ruby -r find -e 'Find.find{|f|...}'

   ruby -i.bak -nple '....'


   Hash.new(0)

   Hash.new{|hash,key| hash[key] = ....}

are very sweet


John Carter                             Phone : (64)(3) 358 6639
Tait Electronics                        Fax   : (64)(3) 359 4632
PO Box 1645 Christchurch                Email : john.carter@tait.co.nz
New Zealand
3bb23e7770680ea44a2d79e6d10daaed?d=identicon&s=25 M. Edward (Ed) Borasky (Guest)
on 2007-02-09 04:42
(Received via mailing list)
Carl Lerche wrote:
>
I've never actually looked at the code that does all the work, but my
favorite bit of Ruby code from what it actually does is "Rake".

--
M. Edward (Ed) Borasky, FBG, AB, PTA, PGS, MS, MNLP, NST, ACMC(P)
http://borasky-research.blogspot.com/

If God had meant for carrots to be eaten cooked, He would have given
rabbits fire.
7aa3c32f034122ff929be64f5de237e7?d=identicon&s=25 Luciano Ramalho (Guest)
on 2007-02-09 07:05
(Received via mailing list)
That's a very nice little demo of Ruby's charm, John.

Cheers!

Luciano
7aa3c32f034122ff929be64f5de237e7?d=identicon&s=25 Luciano Ramalho (Guest)
on 2007-02-09 07:18
(Received via mailing list)
John's snipped is brilliant. I just thought the last line could be like
this:

######

# Ruby is Objects all the way down and open for extension...
class Integer
  def factorial
    return 1 if self <= 1
    self * (self-1).factorial
  end
end

puts 1000.factorial

######

Using puts makes it work outside of irb, and 1000.factorial shows off
Bignum.

It's a pity the factorial method can't be named just "!"...

Cheers,

Luciano
45196398e9685000d195ec626d477f0e?d=identicon&s=25 Trans (Guest)
on 2007-02-09 08:42
(Received via mailing list)
On Feb 8, 3:49 pm, "Carl Lerche" <carl.ler...@gmail.com> 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!

  class Functor < Proc
    private *instance_methods.select { |m| m !~ /(^__|^\W|^binding
$)/ }

    def initialize(&function)
      super(&function)
    end

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

usage example:

  f = Functor.new { |op, x| x.send(op, x) }
  f + 1  #=> 2
  f + 2  #=> 4
  f + 3  #=> 6
  f * 1  #=> 1
  f * 2  #=> 2
  f * 3  #=> 9

T.
7f891fbe8e3bae7f9fe375407ce90d9d?d=identicon&s=25 Harold Hausman (Guest)
on 2007-02-09 09:00
(Received via mailing list)
On 2/9/07, Carl Lerche <carl.lerche@gmail.com> 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 clearly remember this thing making me smile as I wrote it
# of course, it's imperfect, as is everything.
class LSystem
  attr_reader :output

  def initialize( in_axiom, in_rules, in_iterations = 0 )
    @axiom = in_axiom
    @output = in_axiom
    @rules = in_rules

    in_iterations.times do iterate end

    return @output
  end

  def iterate
    temp_string = ""
    @output.scan( /./ ) do |letter|
      rule_hit = false
      @rules.each do |rule|
        if( letter[ rule[0] ] )
          rule_hit = true
          temp_string << rule[1]
        end
      end
      if( not rule_hit )
        temp_string << letter
      end
    end
    @output = temp_string
  end
end

## Example usage:
require 'LSystem'

the_rules = [
  [ /F/, "" ],
  [ /Y/, "+FX--FY+" ],
  [ /X/, "-FX++FY-" ]
]

the_system = LSystem.new( "FX", the_rules, 10 )

p the_system.output

## Of course, the output isn't very useful without a turtle graphics
system. ;)

Regards,
-Harold
93d566cc26b230c553c197c4cd8ac6e4?d=identicon&s=25 Pit Capitain (Guest)
on 2007-02-09 09:28
(Received via mailing list)
Harold Hausman schrieb:
> On 2/9/07, Carl Lerche <carl.lerche@gmail.com> 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!"
>
> (... code sample ...)
>
> ## Of course, the output isn't very useful without a turtle graphics
> system. ;)

Harold, the output might not be useful, but at least it's interesting.
Do you have a picture of what it would look like?

Regards,
Pit
A2b2f4ee23989dc68529baef9cbddcd6?d=identicon&s=25 Julian Tarkhanov (Guest)
on 2007-02-09 09:43
(Received via mailing list)
On Feb 8, 2007, at 9:49 PM, Carl Lerche wrote:

> I'd like to see some of them!

within_transaction do | cursor |
    raise "We have a problem" unless cursor.connected?
    @result = db.find(id) || db.find(DEFAULT_RECORD)
end
7f891fbe8e3bae7f9fe375407ce90d9d?d=identicon&s=25 Harold Hausman (Guest)
on 2007-02-09 09:52
(Received via mailing list)
On 2/9/07, Pit Capitain <pit@capitain.de> wrote:
>
> Harold, the output might not be useful, but at least it's interesting.
> Do you have a picture of what it would look like?
>

I do!
http://www.danceliquid.com/images/LS/Dragon.png

Also, here's some related information:
http://www.math.okstate.edu/mathdept/dynamics/lecn...

(:,
-Harold
6b0967f63d03e99b6c07a3f5ed224c77?d=identicon&s=25 Erik Veenstra (Guest)
on 2007-02-09 10:04
(Received via mailing list)
> f * 2 #=> 2

2 or 4?

What about initialize? Couldn't it be skipped?

gegroet,
Erik V. - http://www.erikveen.dds.nl/
6e68d0d2428a6366d12e91273a1b8788?d=identicon&s=25 S.Volkov (Guest)
on 2007-02-09 10:21
(Received via mailing list)
"Carl Lerche" <carl.lerche@gmail.com> wrote in message
news:ab90312e0702081249ib5fcd61y924299d020f48526@mail.gmail.com...
>
> I'd like to see some of them!

my 2c:

###
Fibonacci = Hash.new{ |ht, k| ht[k] = k<2 ? 1 : ht[k-1] + ht[k-2] }
# Sample
p Fibonacci[100]
#-> 573147844013817084101

###
class String
    # define new String method for 'array' springs replacement
    def gsubs_a originals, replacements
        # create replacements table
        orig2repl = Hash[ *originals.zip( replacements ).flatten ]
        # regexp matching any original
        regexp = /#{originals.map{ |s| Regexp.escape s }.join( '|' )}/
        # substitute each original with replacement from table
        self.gsub( regexp ){ |orig| orig2repl[ orig ] }
    end
end
# Sample
puts "AB[^1-2$].XY".gsubs_a( ["AB", "1-2", "XY", "."], ["CC", "99",
"ZZ",
"+"] )
#-> CC[^99$]+ZZ

enjoy!
Sergey
45196398e9685000d195ec626d477f0e?d=identicon&s=25 Trans (Guest)
on 2007-02-09 11:03
(Received via mailing list)
On Feb 9, 4:03 am, "Erik Veenstra" <erikv...@gmail.com> wrote:
> > f * 2 #=> 2
>
> 2 or 4?

yes that's a typo -- it should be 4.

> What about initialize? Couldn't it be skipped?

how so?

T.
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2007-02-09 11:35
(Received via mailing list)
On 2/8/07, Carl Lerche <carl.lerche@gmail.com> wrote:
> -carl
Without hesitation my favorite is http://rubyquiz.com/quiz67.html
and some of the solutions.
Ara's king ;)


--
6b0967f63d03e99b6c07a3f5ed224c77?d=identicon&s=25 Erik Veenstra (Guest)
on 2007-02-09 11:40
(Received via mailing list)
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... ;]

gegroet,
Erik V. - http://www.erikveen.dds.nl/

----------------------------------------------------------------

 require "test/unit"

 class Functor < Proc
   private *instance_methods.select { |m| m !~ /(^__|^\W|^binding$)/ }

   #def initialize(&function)
     #super(&function)
   #end

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

 class TestFunctor < Test::Unit::TestCase
   def test_it
     f = Functor.new { |op, x| x.send(op, x) }

     assert_equal(2, f+1)
     assert_equal(4, f+2)
     assert_equal(6, f+3)
     assert_equal(1, f*1)
     assert_equal(4, f*2)
     assert_equal(9, f*3)
   end
 end

----------------------------------------------------------------

 $ ruby functor.rb
 Loaded suite functor
 Started
 .
 Finished in 0.0 seconds.

 1 tests, 6 assertions, 0 failures, 0 errors
93d566cc26b230c553c197c4cd8ac6e4?d=identicon&s=25 Pit Capitain (Guest)
on 2007-02-09 12:22
(Received via mailing list)
Harold Hausman schrieb:
> On 2/9/07, Pit Capitain <pit@capitain.de> wrote:
>> Do you have a picture of what it would look like?
>
> I do!
> http://www.danceliquid.com/images/LS/Dragon.png
>
> Also, here's some related information:
> http://www.math.okstate.edu/mathdept/dynamics/lecn...

Thanks for the picture and the interesting read. In return, here's a
simpler version of your iterate method. This only works for context-free
L-systems and assumes the rules are given as a hash, but its much
shorter:

   class LSystem
     def iterate
       @output.gsub!( /./ ) { |letter| @rules[ letter ] || letter }
     end
   end

   the_rules = {
     "F" => "",
     "Y" => "+FX--FY+",
     "X" => "-FX++FY-",
   }

Regards,
Pit
7f891fbe8e3bae7f9fe375407ce90d9d?d=identicon&s=25 Harold Hausman (Guest)
on 2007-02-09 13:58
(Received via mailing list)
On 2/9/07, Pit Capitain <pit@capitain.de> 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. :P

And *that* is one of my favorite parts about Ruby.

Highest Regards,
-Harold
45196398e9685000d195ec626d477f0e?d=identicon&s=25 Trans (Guest)
on 2007-02-09 14:30
(Received via mailing list)
On Feb 9, 5:39 am, "Erik Veenstra" <erikv...@gmail.com> 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.
94cc3e46cfc5bc361e409e2e884ecfa4?d=identicon&s=25 Drew Olson (dfg59)
on 2007-02-09 19:11
Carl Lerche 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
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 unknown (Guest)
on 2007-02-09 19:23
(Received via mailing list)
Hi --

On Fri, 9 Feb 2007, Carl Lerche 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
617b624fa01db9f6440439f3740b35e9?d=identicon&s=25 Marcello Barnaba (Guest)
on 2007-02-10 00:12
(Received via mailing list)
Hi,

On Thursday 08 February 2007 21:49, Carl Lerche 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)
63529e6fbb35dde336d471b569b84d87?d=identicon&s=25 Rodrigo Bermejo (rbermejo)
on 2007-02-10 01:01
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.
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2007-02-10 01:15
(Received via mailing list)
On Feb 9, 2007, at 6:01 PM, Rodrigo Bermejo 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 Gray II
E7559e558ececa67c40f452483b9ac8c?d=identicon&s=25 Gary Wright (Guest)
on 2007-02-10 02:10
(Received via mailing list)
On Feb 8, 2007, at 3:49 PM, Carl Lerche 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 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
E20e89d58211a3631842daecc1245de2?d=identicon&s=25 Ilmari Heikkinen (Guest)
on 2007-02-10 04:41
(Received via mailing list)
On 2/8/07, Carl Lerche <carl.lerche@gmail.com> 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]
E0526a6bf302e77598ef142d91bdd31c?d=identicon&s=25 Daniel DeLorme (Guest)
on 2007-02-10 05:18
(Received via mailing list)
Carl Lerche 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
C06869c119472a139eb163b72040b0db?d=identicon&s=25 Bertram Scharpf (Guest)
on 2007-02-10 06:04
(Received via mailing list)
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
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 Brian Candler (Guest)
on 2007-02-10 15:08
(Received via mailing list)
On Sat, Feb 10, 2007 at 08:10:52AM +0900, Marcello Barnaba 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 :-)
http://tryruby.hobix.com/
617b624fa01db9f6440439f3740b35e9?d=identicon&s=25 Marcello Barnaba (Guest)
on 2007-02-10 16:51
(Received via mailing list)
Hi,

On Saturday 10 February 2007 15:07, Brian Candler wrote:
> > 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
  >> 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 ;) 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
58479f76374a3ba3c69b9804163f39f4?d=identicon&s=25 Eric Hodel (Guest)
on 2007-02-10 21:49
(Received via mailing list)
On Feb 9, 2007, at 16:01, Rodrigo Bermejo 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
D812408537ac3a0fa2fec96eb8811559?d=identicon&s=25 John Carter (johncarter)
on 2007-02-10 21:57
(Received via mailing list)
On Fri, 9 Feb 2007, Luciano Ramalho 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. :-)

>> 720
John Carter                             Phone : (64)(3) 358 6639
Tait Electronics                        Fax   : (64)(3) 359 4632
PO Box 1645 Christchurch                Email : john.carter@tait.co.nz
New Zealand
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2007-02-10 22:00
(Received via mailing list)
On 2/10/07, Eric Hodel <drbrain@segment7.net> wrote:
>
> On Feb 9, 2007, at 16:01, Rodrigo Bermejo 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
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2007-02-10 22:02
(Received via mailing list)
On 2/10/07, John Carter <john.carter@tait.co.nz> 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. :-)



It was me(1) who said: "When stealing, steal only from the best" ;)

Stolen from Faulkner if I recall correctly.
Robert
This topic is locked and can not be replied to.