PMc
PMc

Reputation: 118

ruby: howto use multiple boolean options and keep the code readable

I need to process a couple of boolean options, and I am trying to do it like it is usually done in C:

  DICT    = 0x000020000
  FILTER  = 0x000040000
  HIGH    = 0x000080000
  KEEP    = 0x000100000
  NEXT    = 0x000200000

I can now assign arbitrary options to a Integer variable, and test for them:

action if (opts & HIGH|KEEP) != 0

But this looks ugly and gets hard to read. I would prefer writing it like

action if opts.have HIGH|KEEP

This would require to load have method onto Integer class.

The question now is: where would I do that, in order to keep this method contained to the module where those options are used and the classes that include this module? I don't think it's a good idea to add it globally, as somebody might define another have somewhere.

Or, are there better approaches, for the general task or for the given use-case? Adding a separate Options class looks like overkill - or should I?

Upvotes: 0

Views: 77

Answers (1)

Stefan
Stefan

Reputation: 114138

You can use anybits?:

action if opts.anybits?(HIGH|KEEP)

The methods returns true if any bits from the given mask are set in the receiver, and false otherwise.

Upvotes: 2

Related Questions