Rails - return an array of months for a select tag

前端 未结 10 2520
谎友^
谎友^ 2021-02-07 10:02

I\'m in an app that is on Rails 2.3.8, and need to return an array of month names and numbers to be plugged into an options_for_select statement. What I\'ve got so far is kind

10条回答
  •  你的背包
    2021-02-07 10:29

    # 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
    

提交回复
热议问题