Tuesday, July 04, 2006

Ruby : to_eng Integer class extension

Here's the "English Number" method implemented in a more useful form; as an extension to the Integer class. It now works with negative numbers to. The usage is simple.




puts 0.to_eng(0) # arg is 0 for British, 1 for American
puts 12.to_eng(1)
puts -54.to_eng(1)
puts (10**600).to_eng(0)






# extend the Integer class with a "to english" method

class Integer

def to_eng scale

number = self.abs

if number == 0
return 'zero'
end

# ... code removed see previous post

if write > 0

exps = write.to_eng(scale)

# ...

end
# ...

if self<0
numString = "Minus " + numString
end

# Now we just return "numString"...
numString

end

end

No comments: