简体   繁体   English

rails MONTHNAMES to_s

[英]rails MONTHNAMES to_s

this is the problem: 这就是问题:

inside a lib i need to print MONTHNAMES to string 在lib里面我需要将MONTHNAMES打印到字符串

if i try 如果我试试

Date::MONTHNAMES.inspect

result is 结果是

=> "[nil, \\"January\\", \\"February\\", \\"March\\", \\"April\\", \\"May\\", \\"June\\", \\"July\\", \\"August\\", \\"September\\", \\"October\\", \\"November\\", \\"December\\"]" =>“[nil,\\”1月\\“,”2月“,”3月“,”4月“,”5月“,”6月“,”7月“,”八月“,”九月“,”十月“,”十一月“,”十二月“,”

that's good 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 谢谢

...也给你所有月份(没有第一个零)。

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

给你所有月份(没有第一个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). 如错误消息中所示, Date::MONTHNAMES是一个冻结对象,因此您无法对其进行修改( shift将通过移除第一个元素来修改它)。 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?}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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