Skip to content

Instantly share code, notes, and snippets.

@norman
Created May 5, 2010 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save norman/391224 to your computer and use it in GitHub Desktop.
Save norman/391224 to your computer and use it in GitHub Desktop.
# Here's a piece of functionality I need to access often inside my library. It breaks an int
# into an array of bits, with each bit's position in the int corresponding to its array
# index. This gives me a consise way to check to see if lots of different bits are set.
123.to_s(2).reverse.split("").map(&:to_i)
# So, where do I put this? Should I monkey-patch Fixnum?
class Fixnum
def to_bit_array
to_s(2).reverse.split("").map(&:to_i)
end
end
# I'd prefer not to, because some people get pissed when libraries add
# functionality all over the place. My library is about Phonology, so
# it ideally should not be patching Fixnum. That would be unexpected.
# Should I declare a global function? That too is ugly.
#
# How about putting it inside a module in my namespace?
module Phonology
def self.bit_array(int)
int.to_s(2).reverse.split("").map(&:to_i)
end
end
# The only problem here, is now I've got an ugly, off-topic method that
# appears to be a part of the public API I'm exposing.
# How about adding it to a Utils model as a private method and mix that into
# all my classes that need it?
module Phonology
module Utils
private
def bit_array(int)
int.to_s(2).reverse.split("").map(&:to_i)
end
end
end
# That too is uncomfortable, because I have to mix it in, over and over again.
# OK, how about I make a class that extends Fixnum and add this as an instance
# method? Ummm... no thanks.
# What I would *really* like to do, is add this to the top-level of my
# namespace, but make it protected so that I can use it anywhere in my namespace,
# but not have it show up as a part of the public API. But I can't, because
# Ruby's `protected` doesn't work like that.
module Phonology
protected
def self.bit_array(int)
int.to_s(2).reverse.split("").map(&:to_i)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment