Your favorite bit of ruby code?

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

···

--
EPA Rating: 3000 Lines of Code / Gallon (of coffee)

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

# 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

···

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

···

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

···

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!"

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!

thanks,
-carl

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.

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.

···

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!

# 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. :wink:

Regards,
-Harold

···

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!

within_transaction do | cursor |
    raise "We have a problem" unless cursor.connected?
    @result = db.find(id) || db.find(DEFAULT_RECORD)
end

···

On Feb 8, 2007, at 9:49 PM, Carl Lerche wrote:

I'd like to see some of them!

--
Julian 'Julik' Tarkhanov
please send all personal mail to
me at julik.nl

"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

Without hesitation my favorite is Ruby Quiz - metakoans.rb (#67)
and some of the solutions.
Ara's king :wink:

···

On 2/8/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!

thanks,
-carl

--

EPA Rating: 3000 Lines of Code / Gallon (of coffee)

--
We have not succeeded in answering all of our questions.
In fact, in some ways, we are more confused than ever.
But we feel we are confused on a higher level and about more important
things.
-Anonymous

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

···

--
Posted via http://www.ruby-forum.com/\.

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

···

On Fri, 9 Feb 2007, Carl Lerche wrote:

--
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)

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\)

···

On Thursday 08 February 2007 21:49, Carl Lerche wrote:
--
pub 1024D/8D2787EF 723C 7CA3 3C19 2ACE 6E20 9CC1 9956 EB3C 8D27 87EF

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

···

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!"

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]

···

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!"

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

Hi,

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

···

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

--
Bertram Scharpf
Stuttgart, Deutschland/Germany
http://www.bertram-scharpf.de

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

···

On 2/8/07, John Carter <john.carter@tait.co.nz> wrote:

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

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

Cheers!

Luciano

···

On 2/8/07, John Carter <john.carter@tait.co.nz> wrote:

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