Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Ruby is beautiful

Name: Anonymous 2009-08-26 15:25

class Cycle
    def cycle(*args)
      args[((@_cycles ||= Hash.new(-1))[args.hash] += 1) % args.size]
    end
end

More beautiful code plees?

Name: UMH memesmith !gNlkr4vCuc 2009-08-26 22:22

# I documented this just for you, /prog/.  What now, >>1?
class Cycle
  def cycle(*args)      # All args are passed as an array object
    # Assign a new hashtable to the @cycles instance variable if it
    # doesn't already exist.  If you try to access @cycles[x] for any
    # key x that is not already in @cycles, a default value of -1 will
    # automatically be inserted.  By the way, there's absolutely no
    # reason to use an underscore at the beginning of an ivar name.
    # The @ already marks it as an ivar.
    @cycles ||= Hash.new(-1)

    h = args.hash       # Hashcode, not array-as-hashtable
    @cycles[h] += 1     # Tragically, there's no ++ in ruby

    # Have you studied your modular arithmetic today?  By the way,
    # this is an implicit return statement
    args[@cycles[h] % args.size]
  end
end

# Now to demonstrate what it actually does
foo = Cycle.new
foo.cycle :hax, :my, :anus # => :hax
foo.cycle :hax, :my, :anus # => :my
foo.cycle :achieve, :satori # => :achieve
foo.cycle :hax, :my, :anus # => :anus
foo.cycle :hax, :my, :anus # => :hax

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List