Skip to content

Instantly share code, notes, and snippets.

@trans
Created August 24, 2010 14:26
Show Gist options
  • Save trans/547636 to your computer and use it in GitHub Desktop.
Save trans/547636 to your computer and use it in GitHub Desktop.
Optimize #succ for skipping steps
# The idea here is that #succ could take an optional parameter
# to help optimize certain (albeit rare) cases when skipping steps
# is required.
class Fixnum
# Allows #succ to take _n_ increments.
#
# 3.succ(2) #=> 5
#
# CREDIT: Trans
def succ(n=1)
self + n
end
# Provides #pred as the opposite of #succ.
#
# 3.pred(2) #=> 1
#
# CREDIT: Trans
def pred(n=1)
self - n
end
end
class String
alias_method :succ1, :succ
# Allows #succ to take _n_ step increments.
#
# "abc".succ #=> "abd"
# "abc".succ(4) #=> "abg"
# "abc".succ(24) #=> "aca"
#
# TODO: Optimize String#succ(n) algorithm.
#
# CREDIT: Trans
def succ(n=1)
s = self
n.times { s = s.succ1 }
s
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment