Created
January 10, 2012 19:31
-
-
Save djberg96/1590688 to your computer and use it in GitHub Desktop.
Converting constants to human readable strings
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
class Foo | |
Alpha = 1 | |
Beta = 2 | |
Gamma = 4 | |
@@opts = { | |
Alpha => 'alpha', | |
Beta => 'beta', | |
Gamma => 'gamma' | |
} | |
def display(num) | |
flags = num | |
str = '' | |
@@opts.each{ |key,val| | |
if flags & key > 0 | |
if str.empty? | |
str << val | |
else | |
str << ",#{val}" | |
end | |
flags &= ~key | |
end | |
} | |
p str | |
end | |
end | |
Foo.new.display(Foo::Alpha) # Works | |
Foo.new.display(Foo::Alpha|Foo::Beta) # Works | |
Foo.new.display(Foo::Alpha|Foo::Beta|Foo::Gamma) # Works after all with valid values. :) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment