Skip to content

Instantly share code, notes, and snippets.

@syntacticsugar
Forked from jjb/commaifier.rb
Last active December 15, 2015 04:29
Show Gist options
  • Save syntacticsugar/5202248 to your computer and use it in GitHub Desktop.
Save syntacticsugar/5202248 to your computer and use it in GitHub Desktop.
def modulo_3?(number)
# (number % 3).zero?
number.modulo(3).zero? # i guess this is more idiomatic Ruby, though I like the previous better
end
def commify(number)
reversed = number.to_s.reverse
number_size = number.to_s.size
result = ""
number_size.times do |i|
result << reversed[i]
result << "," if modulo_3?(i + 1)
end
result.reverse
end
# > commify(25164150)
# => "25,164,150"
# > commify(1234567890)
# => "1,234,567,890"
# goal: get a number like 25164150
# and transform it to: 25,164,150
# =begin
# 1) number.to_s.split("").length
# 2) start from end, count multiples of 3
# 3) insert comma
# 4) turn array back into a string
# .join(",")
# x.unshift(",")unless (x % 3 != 0)
# =end
# number = 11 223 344 556
kazu = [1,1,2,2,3,3,4,4,5,5,6]
# goal = 11,223,344,556
bloated = kazu.reverse.join.split("") # yields array of many strings
threes = 0.upto(kazu.length).find_all { |index| (index % 3).zero? }[1..-1]
# threes --> [3,6,9] # these are the comma-relevent indices
print "the solution is: \n"
puts bloated[threes.last..-1].reverse.join + "," + threes.map { |n| (n-3)..(n-1)}.map {|r| bloated[r]}.map(&:join).join(',').reverse
# STABBY LAMBDA TIME!!!!!!!!!!!
commify = ->(n) {
bloated = n.to_s.reverse.split("")
threes = 0.upto(n.to_s.split("").length).find_all { |index| (index % 3).zero? }[1..-1]
bloated[threes.last..-1].reverse.join + "," + threes.map { |n| (n-3)..(n-1)}.map {|r| bloated[r]}.map(&:join).join(',').reverse
}
puts "\n\nBut the COOL lambda solution is: #{commify[11223344556]}" + " !!!!!"
# 1 + 2
# 1.+(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment