Skip to content

Instantly share code, notes, and snippets.

@rodrigopinto
Forked from hgmnz/number_percent_extension.rb
Created January 23, 2013 21:38
Show Gist options
  • Save rodrigopinto/4613825 to your computer and use it in GitHub Desktop.
Save rodrigopinto/4613825 to your computer and use it in GitHub Desktop.
module NumberPercentageExtension
module InstanceMethods
# the idea converting english to numbers taken from http://www.ruby-forum.com/topic/132735#591799
ENGLISH_VALUE = {}
%w| zero one two three four five six seven eight nine ten eleven
twelve thirteen fourteen fifteen sixteen seventeen eighteen
nineteen |.each_with_index{ |word,i| ENGLISH_VALUE[word] = i }
%w| zero ten twenty thirty forty fifty sixty seventy eighty
ninety|.each_with_index{ |word,i| ENGLISH_VALUE[word] = i*10 }
ENGLISH_VALUE['hundred'] = 100
def percent_method?(method)
tokens = method.to_s.split('_')
return false if tokens.size < 2
is_percent = tokens[-1] == 'percent'
tokens[0..-2].collect { |word| is_percent &&= ENGLISH_VALUE.has_key?(word) }
return is_percent
end
def method_missing(method, *args)
if percent_method?(method)
method.to_s.split('_')[0..-2].map { |word| ENGLISH_VALUE[word] }.sum * self / 100.to_f
else
raise "NoMethodError: undefined method #{method} for class #{self.class.name}"
end
end
def respond_to?(method)
return true if percent_method?(method)
super(method)
end
end
Numeric.class_eval do
include InstanceMethods
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment