Created
April 13, 2011 16:12
-
-
Save catwell/917844 to your computer and use it in GitHub Desktop.
Let's try to refactor info_string, keeping it functional and short
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# eg.: @slots = Hash[[5,19,20,32,21,28].zip([:new]*6)] | |
def info_string | |
"#{self.to_s.ljust(25)} slots:" + @slots.keys.sort.reduce([]){|a,b| | |
if a.empty? || !(a[-1][1]+1 == b) | |
a << [b,b] | |
else | |
a[-1][1] = b | |
a | |
end | |
}.map{|x| (x[0] == x[1]) ? x[1] : "#{x[0]}-#{x[1]}"}.join(",") | |
end | |
# another style... | |
def info_string | |
nums = @slots.keys.sort | |
start = stop = nums.first | |
slots = [] | |
(nums[1..-1]+[nums.last+2]).each do |x| | |
if x == stop + 1 | |
stop += 1 | |
else | |
slots << ((start == stop) ? start : "#{start}-#{stop}") | |
start = stop = x | |
end | |
end | |
"#{self.to_s.ljust(25)} slots:" + slots.join(",") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fair answer - that's what I get for throwing together something in a rush and not testing it :-)