Matt Elhotiby
Matt Elhotiby

Reputation: 44086

How do I return this ruby array

I have a table named Player in my Rails app, and on the table, there are seven boolean attributes.

monday: true, tuesday: false, wednesday: true, thursday: false, friday: false, saturday: true, sunday: false

What is the best way to return an array with all the days that are true with ActiveRecord? I want to return:

["monday", "wednesday", "saturday"]

Any ideas on an efficient way to do this? I am drawing a blank? Player.first.map?

Upvotes: 2

Views: 101

Answers (2)

You can solve this issue with something like:

p = Player.first

p.attributes.select{|k,v| v == true}.keys

Hope it helps.

Upvotes: 2

mikej
mikej

Reputation: 66343

Assuming you mean that there are 7 attributes on the model you could add a method to Player like

def days
  ["monday", "tuesday", "wednesday", "thursday", "friday", 
    "saturday", "sunday"].select { |day| attributes[day] }
end

So for your example it would just be

Player.first.days # => e.g. ["monday", "wednesday", "saturday"]

This is making use of the ActiveRecord attributes method on a model instance which returns a Hash of attribute names to values.


As InternetSeriousBusiness has commented, there is already an array of the day names defined on the Date class so you could use that and avoid listing the days yourself, but note that the days in there start with an initial capital letter so you'd need a downcase to match your attribute names e.g.

Date::DAYNAMES.select { |day| attributes[day.downcase] }

Upvotes: 3

Related Questions