Articles

A Ruby porting challenge

In Language design on January 27, 2011 by Matt Giuca Tagged: ,

Having an in-agreement discussion with Tim about Ruby. I’ll write a full post later, but for now (to make sure I don’t make an ass of myself later, if anyone has a better answer), who can port this small Python function to Ruby?

def allprefixes(x):
    prefixes = []
    for i in range(len(x)+1):
        prefixes.append(x[0:i])
    return prefixes

Expected output:

>>> allprefixes([1,2,3])
[[], [1], [1, 2], [1, 2, 3]]

See the problem? Any non-hacky solutions? (I have mine, but it is hacky, and I’ll save it for the follow-up post.)

Edit: Arg, OK I just found out about Ruby’s … operator. That makes things significantly easier (having previously known only about the .. operator). Never mind then! But it is still a nasty default.

Advertisements

3 Responses to “A Ruby porting challenge”

  1. My solution is therefore rather simple after all:

    def allprefixes(x)
        prefixes = []
        for i in 0..x.length do
            prefixes << x[0...i]
        end
        return prefixes
    end

    Having not known about the … operator, the insidious .. operator would leave me having to special-case the i==0 case, due to it's silly end-inclusion combined with the Python "negative numbers count from the end" rule.

  2. But it looks less simple once again next to the list comprehension version of the original python example šŸ™‚

    def allprefixes(x):
    return [x[0:i] for i in xrange(len(x)+1)]

    • Oh absolutely. I just wanted to pose the question in a way that was at least Ruby-like. (Since the point was about the range operator, not about list comprehensions.)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: