Forum: Ruby Python Vs Ruby ( again )

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.
Cf8586cf56fec72eb20a52e6797fea31?d=identicon&s=25 Brad Phelan (Guest)
on 2007-07-26 16:53
(Received via mailing list)
There was a discussion a while back in trying to get Ruby looking like
Python using an indentation scheme and I posted a possible solution to
that

http://xtargets.com/snippets/posts/show/68

There is also the Lazibi library ( sorry no link .. google it ) that
does a similar thing.

I thought to be fair I'd have a hack in the opposite direction and see
if I could emulate Ruby's block notation in Python without
preprocessing. Turns out that you can get pretty close though if a bit
ugly due to the statement vs expression nature of the language.

Note that in python a return statement from within a function with a
yield statement is illegal some some ugly workaround is necessary.

A few short examples .....

from ruby import rubyfi

#Ruby's inject method
@rubyfi
def inject(ret, iter, a = 0):
    for x in iter:
       a = yield a, x
    ret(a)

#Ruby's collect method
@rubyfi
def collect(ret, iter):
    r = []
    for x in iter:
       x = yield x,
       r.append(x)
    ret(r)

# Do a sum over a range
for r, s, x in inject ( range (1,6), 1 ) :
    r(s+x)
print r()

# Generate a list
for r, s, x in inject ( range (1,6), [] ) :
    s.append(x*x)
    r(s)
print r()

# Collect some items
for r, x in collect ( range (1,6) ) :
    r(x+x)
print r()

The library and some details is at

http://xtargets.com/snippets/posts/show/74

Can this be developed a little further or a little cleaner?
This topic is locked and can not be replied to.