[ACCEPTED]-Rails - return an array of months for a select tag-select

Accepted answer
Score: 37

Try this!

@months = [['-', '']]
(1..12).each {|m| @months << [Date::MONTHNAMES[m], m]}

0

Score: 19
Date::MONTHNAMES.each_with_index.collect{|m, i| [m, i]}
=> [[nil, 0], 
    ["January", 1], 
    ["February", 2], 
    ["March", 3], 
    ["April", 4], 
    ["May", 5], 
    ["June", 6], 
    ["July", 7], 
    ["August", 8], 
    ["September", 9], 
    ["October", 10], 
    ["November", 11], 
    ["December", 12]]

Abbreviated selection with default option

Date::ABBR_MONTHNAMES.compact.each_with_index.collect{|m, i| [m, i+1]}
                     .insert(0, ['Please Select', nil])
=> [["Please Select", nil], 
    ["Jan", 1], 
    ["Feb", 2], 
    ["Mar", 3], 
    ["Apr", 4], 
    ["May", 5], 
    ["Jun", 6], 
    ["Jul", 7], 
    ["Aug", 8], 
    ["Sep", 9], 
    ["Oct", 10], 
    ["Nov", 11], 
    ["Dec", 12]]

0

Score: 11

You can use rails helper select_month, like:

select_month(Date.today)

0

Score: 2

This is my solution for you, in case you work with I18n-based projects, that requires 1 multilingual features:

def month_array
  # Gets the first day of the year
  date = Date.today.beginning_of_year
  # Initialize the months array
  months = {}

  # Iterate through the 12 months of the year to get it's collect
  12.times do |i| # from 0 to 11
    # Get month name from current month number in a selected language (locale parameter)
    month_name = I18n.l(date + i.months, format: '%B', locale: :en).capitalize
    months[month_name] = i + 1
  end
  return months
end

# => {"January"=>1, "February"=>2, "March"=>3, "April"=>4, "May"=>5, "June"=>6, "July"=>7, "August"=>8, "September"=>9, "October"=>10, "November"=>11, "December"=>12}

Regards

Score: 2

Here's a sexy way to get the months only if 1 that's all you want:

Date::MONTHNAMES.slice(1..-1).map(&:to_sym)
Score: 1

Working for ROR 4

select_month(0 , prompt: 'Choose month')

0

Score: 1

If you want it to be translated to the selected 1 language.

t("date.month_names")
Score: 1

Found this nifty way to shift off the first 3 nil but return a new collection of months. You 2 cannot use shift on it since that would 1 try to modify the frozen variable.

Date::MONTHNAMES.drop(1)
Score: 0

Try it

<% (1..12).each do |month|%>
  <%= link_to t('date.month_names')[month], '#' %>
<% end %>

0

Score: 0
# alternative 1 
Date::MONTHNAMES.compact.zip(1.upto(12)).to_h

# alternative 2
Date::MONTHNAMES.compact.zip([*1..12]).to_h

Outputs:

{"January"=>0, "February"=>1, "March"=>2, "April"=>3, "May"=>4, "June"=>5, "July"=>6, "August"=>7, "September"=>8, "October"=>9, "November"=>10, "December"=>11}

Example:

# using simple_form
f.input :month, collection:  Date::MONTHNAMES.compact.zip(1.upto(12)).to_h

0

More Related questions