Michael Liu
Michael Liu

Reputation: 1131

Ruby - Instantiate array values based on boolean variables

My user model has seven boolean columns (:mon, :tue... :sat, :sun) for each day of the week. In one of the user methods I need to create an array of strings like ["mon", "tue"... "sat", "sun"] for use in time parsing. As you can guess, these array values come from the database columns, and should only be in the array if that column is true.

One way to do it would be manually, like so:

if user.mon
  arr.push("mon")
end

... for every day in the user model. However, I was wondering if there was a cleaner, more efficient way of accomplishing this.

Upvotes: 0

Views: 73

Answers (1)

Chuck
Chuck

Reputation: 237010

I think you want select:

 ["mon", "tue"... "sat", "sun"].select {|day| user.send day }

Upvotes: 1

Related Questions