开发者

rails MONTHNAMES to_s

this is the problem:

inside a lib i need to print MONTHNAMES to string

if i try

Date::MONTHNAMES.inspect

result is

=> "[nil, \"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"]"

that's good 开发者_StackOverflow社区but i don't need the first element, so

month_names = Date::MONTHNAMES
month_names.shift
month_names.inspect

but

ActionView::TemplateError (can't modify frozen array) 

there is any workaround? thanks


...also gives you all month (without the first nil).

Date::MONTHNAMES.compact


Date::MONTHNAMES.slice(1,12).inspect

gives you all month (without the first nil).


As showed in the error message Date::MONTHNAMES is a frozen object so you can not modify it(shift will modify it by ,well, shifting out the first element). You can achieve what you want by:

puts Date::MONTHNAMES[1..-1].inspect


Although the slice/array indexing solution is probably better here, you can always dup a frozen array and work on the copy:

month_names = Date::MONTHNAMES.dup
month_names.shift
month_names.inspect

should give you what you want.


Date::MONTHNAMES.reject{|m| m.nil?}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜