简体   繁体   English

Ruby on Rails:遍历嵌套参数

[英]Ruby on Rails: Iterate Through Nested Params

I want to iterate through submitted params. 我想遍历提交的参数。 Params array could be up to three level. 参数数组最多可以达到三个级别。 Currently I can iterate only first level like this. 目前,我只能像这样迭代第一级。

params[:job].each do |v, k|
    #do something with k value, only if it's string. If it's array then find its string value.
end

How do I iterate params when you don't know what you are expecting? 当您不知道自己期望什么时,如何迭代参数?

One easy way is to use is_a? 一种简单的方法是使用is_a?

if v.is_a? Array
  # do whatever
elsif v.is_a? String
  # do whatever
else
  # something else
end

Some kind of recursive solution might be best here, such as: 某种递归解决方案可能是最好的选择,例如:

def handle_hash hash
  hash.each do |k, v|
    if v.is_a? Hash
      handle_hash v
    elsif v.is_a? String
      # handle string
    end
  end 
end

And then you can just call handle_hash params[:job] 然后,您可以只调用handle_hash params[:job]

def nested_params(nested_hash={})  
      nested_hash.each_pair do |k,v|
        case v
          when String, Fixnum then 
            dosomething(v)
          when Hash then nested_params(v)
          else raise ArgumentError, "Unhandled type #{v.class}"
        end
      end
  end 

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

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