【问题标题】:Loop through array and pass keys to function循环遍历数组并将键传递给函数
【发布时间】:2016-04-12 20:41:58
【问题描述】:

我正在尝试将 events_sections 数组中的每个元素传递给一个函数,但我一直得到 nil,我不确定我在这里做错了什么。

event_sections = ["a_full","b_full","c_full","e_full","h_full","i_full","k_full","z_full"]
    event_sections.each do |key|
       @events[key] = Zlib.inflate(Events_Full_Sections.first."#{key}")
    end 
    render json: @events 

非常感谢您的帮助

【问题讨论】:

  • nil 到底是什么?您是否收到任何其他错误?你确定Events_Full_Sections 不是空白吗?
  • 如果这是 (Events_Full_Sections) 型号名称,我会感到非常惊讶 :)
  • 对,就是型号

标签: ruby-on-rails ruby


【解决方案1】:

我认为您之前没有定义 @events。因此,在循环之前用该变量定义一个空数组:

@events = []

另外,如果Events_Full_Sections 是一个模型,我们不会像您尝试的那样调用带有插值的方法。我们使用send 方法来调用具有str/symbol 名称的方法。像这样:

event_sections = ["a_full","b_full","c_full","e_full","h_full","i_full","k_full","z_full"]
@events = []

event_sections.each do |key|
   @events[key] = Zlib.inflate(Events_Full_Sections.first.send(key))
end 
render json: @events 

我不确定您的数据库结构,所以我认为它会起作用。

您也可以将Events_Full_Sections.first 保存在循环外的变量中,以避免每次都调用 db。

【讨论】:

    猜你喜欢
    • 2016-10-02
    • 2019-03-06
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2017-08-16
    相关资源
    最近更新 更多