Your favorite bit of ruby code?

C

Carl Lerche

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
 
W

Wolfgang Nádasi-Donner

Carl said:
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
 
J

John Carter

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 : (e-mail address removed)
New Zealand
 
J

John Carter

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 : (e-mail address removed)
New Zealand
 
J

John Carter

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 : (e-mail address removed)
New Zealand
 
M

M. Edward (Ed) Borasky

Carl said:
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".
 
L

Luciano Ramalho

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
 
T

Trans

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.
 
H

Harold Hausman

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 :eek:utput

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
 
P

Pit Capitain

Harold said:
(... 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
 
J

Julian Tarkhanov

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
 
S

S.Volkov

Carl Lerche said:
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
 
E

Erik Veenstra

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
 
P

Pit Capitain

Harold said:

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
 
H

Harold Hausman

Harold said:

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-",
}

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

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

Highest Regards,
-Harold
 
T

Trans

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.
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top