Mike Sutton
Mike Sutton

Reputation: 4211

Store an array or hash of booleans in Ruby and Rails

I want to create a set of values in Ruby which I can store and retrieve in a MySQL databse under Rails.

In Delphi I would use:

//Create an enumeration with four possible values
type TColour = (clRed, clBue, clBlack, clWhite);
//Create a set which can hold values from the above enumeration
     TColours = set of TColours;
//Create a variable to hold the set
var MyColours = TColours;
begin
  //Set the variable to hold two values from the enumeration
  MyColours = [clRed, clBlack];
  //MyColours now contains clRed and clBlack, but not clBlue or clWhite

  //Use a typecast to convert MyColours to an integer and store it in the database
  StoreInDatabase(Integer(MyColours));

  //Typecast the Integer back to a set to retrieve it from the database
  MyColours := TColours(RetrieveFromDatabase);
end;

I can then use a typecast to convert to/from an integer.

How would I achieve the same in Ruby/Rails?

Just to clarify, suppose I had a form with check boxes for 'Red', 'Blue', 'Black', 'White'. The user can choose none, one, or more than one value. How to I store and retrieve that set of values?

BTW, another way of doing this in delphi is with bitwise maths:

const
  Red = 1;
  Blue = 2;
  Black = 4;
  White = 8;
var MyColours: Integer;
begin
  MyColours := Red+Black; //(or MyColours = Red or Black)

which can be stored and retrieved as an integer

Upvotes: 0

Views: 2355

Answers (4)

gamov
gamov

Reputation: 3859

Use the nice gem: https://github.com/pboling/flag_shih_tzu

use one integer for all flags, has db search and scopes.

Upvotes: 1

Jonas Elfström
Jonas Elfström

Reputation: 31428

Maybe you find this easier

Colors={:red=>1, :blue=>2, :black=>4, :white=>8}
mix = Colors[:blue] + Colors[:black]
Colors.select{|key,value| value & mix > 0}
=> [[:blue, 2], [:black, 4]]

Upvotes: 0

khelll
khelll

Reputation: 23990

Here is a simple implementation for the bitwise solution:

module Colors
  Red = 1
  Blue = 2
  Black = 4
  White = 8
  ColorsSet = [Red,Blue,Black,White]

  # Mixing valid colors
  def self.mix(*colors) 
    colors.inject{|sum,color| ColorsSet.include?(color) ? color | sum : sum }
  end

  # Get an array of elements forming a mix
  def self.elements(mix)
    ColorsSet.select{|color| color & mix > 0}
  end
end

mix = Colors::mix(Colors::Red,Colors::Blue)

puts mix #=> 3

puts Colors::elements(mix) 
#=> 1
#   2

Upvotes: 3

rnicholson
rnicholson

Reputation: 4588

Based on comments and revised question, sounds like you want try out the Enum Column plugin for Rails. Has a helper, enum_radio(), that would probably be useful in your form.

Upvotes: 1

Related Questions