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

Carl L. 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

On Fri, 9 Feb 2007, 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!”

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 C. Phone : (64)(3) 358 6639
Tait Electronics Fax : (64)(3) 359 4632
PO Box 1645 Christchurch Email : [email protected]
New Zealand

On Fri, 9 Feb 2007, 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!”

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 C. Phone : (64)(3) 358 6639
Tait Electronics Fax : (64)(3) 359 4632
PO Box 1645 Christchurch Email : [email protected]
New Zealand

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 Fri, 9 Feb 2007, 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!”

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 C. Phone : (64)(3) 358 6639
Tait Electronics Fax : (64)(3) 359 4632
PO Box 1645 Christchurch Email : [email protected]
New Zealand

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

Cheers!

Luciano

Carl L. 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.

On Feb 8, 3:49 pm, “Carl L.” [email protected] 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.

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

Harold H. schrieb:

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

(… code sample …)

Of course, the output isn’t very useful without a turtle graphics

system. :wink:

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

On 2/9/07, Carl L. [email protected] 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, Pit C. [email protected] 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!

Also, here’s some related information:
http://www.math.okstate.edu/mathdept/dynamics/lecnotes/node17.html

(:,
-Harold

f * 2 #=> 2

2 or 4?

What about initialize? Couldn’t it be skipped?

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

On Feb 8, 2007, at 9:49 PM, Carl L. 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

On Feb 9, 4:03 am, “Erik V.” [email protected] 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.

“Carl L.” [email protected] wrote in message
news:[email protected]

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

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

-carl
Without hesitation my favorite is http://rubyquiz.com/quiz67.html
and some of the solutions.
Ara’s king :wink:

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

Harold H. schrieb:

On 2/9/07, Pit C. [email protected] 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/lecnotes/node17.html

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