动态创建Rails中4哈希键名 [英] Dynamically creating hash key name in Rails 4

查看:128
本文介绍了动态创建Rails中4哈希键名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以动态地创建一个哈希的键名?我通过以下哈希参数:

Is it possible to dynamically create key names of a hash? I'm passing the following hash parameters:

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)]

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

To check if each parameter exists, I'm using two arrays:

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

不过,我似乎无法弄清楚如何动态地创建params哈希表(第二个键(与数组这里是我到目前为止有:

But, I can't seem to figure out how to dynamically create the params hash (the second key( with the array. Here's what I have so far:

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方法(如上面列出的),但似乎轨不喜欢围绕5I括号。任何帮助是极大AP preciated!

I've tried a bunch of things including the eval method (as listed above) but rails seems to dislike the parentheses around the "5i". Any help is greatly appreciated!

推荐答案

您应该能够做到

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

请注意,你是缺少 .nil?!对象.nil?可缩短至仅仅对象

Note that you were missing the ? on .nil? and that !object.nil? can be shortened to just object

这篇关于动态创建Rails中4哈希键名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆