在Rails 4中动态创建哈希键名

是否可以动态创建哈希的键名? 我传递了以下哈希参数:

params[:store][:store_mon_open(5i)] params[:store][:store_mon_closed(5i)] params[:store][:store_tue_open(5i)] params[:store][:store_tue_closed(5i)] . . . params[:store][:store_sun_open(5i)] params[:store][:store_sun_closed(5i)] 

要检查每个参数是否存在,我使用两个数组:

 days_of_week = [:mon, :tue, ..., :sun] open_or_closed = [:open, :closed] 

但是,我似乎无法弄清楚如何动态创建params散列(第二个键(带数组)。这是我到目前为止所拥有的:

 days_of_week.each do |day_of_week| open_or_closed.each do |store_status| if !eval("params[:store][:store_#{day_of_week}_#{store_status}(5i)").nil [DO SOMETHING] end end end 

我尝试了很多东西,包括eval方法(如上所列),但rails似乎不喜欢围绕“5i”的括号。 任何帮助是极大的赞赏!

你应该能做到的

 if params[:store]["store_#{day_of_week}_#{store_status}(5i)".to_sym] 

请注意,你错过了?.nil? 那个!object.nil? 可以简化为object

假设这是一个HashWithIndifferentAccess,您应该能够通过字符串访问它,就像使用符号一样。 从而:

 days_of_week.each do |day_of_week| open_or_closed.each do |store_status| key = "store_#{day_of_week}_#{store_status}(5i)" unless params[:store][key] # DO SOMETHING end end end 

如果它不是HashWithIndifferentAccess那么您应该只能调用key.to_sym将其转换为符号。