简体   繁体   中英

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.

我认为您要select

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM