递归访问哈希中数组的最后一个值

时间:2017-01-15 05:04:24

标签: ruby

输入可能来自string内的arrayhash

然而,

  • Hash可以是递归的。
  • Array可能有多个值。

实施例

  # ex.1  "name must be a string"
  # ex.2 {"name"=>["name must be a string"]}
  # ex.3  {"name"=>["name must be a string", "name must be greater than 3"]}
  # ex.4 {"payment"=> {"currency"=>["currency must be a jpy"]}}
  # ex.5 {"payment"=> {"currency"=>["currency must be a jpy", "currency must be string"]}}

我喜欢渲染字符串或数组中的每个最后一个值。

  # ex.1 method(x) => "name must be a string"
  # ex.2 method(x) => "name must be a string"
  # ex.3 method(x) => "name must be a string"/ "name must be greater than 3"
  # ex.4 method(x) => "currency must be a jpy"
  # ex.5 method(x) => "currency must be a jpy"/ "currency must be string"

2 个答案:

答案 0 :(得分:1)

free(new_str);

答案 1 :(得分:0)

def last_values(val)
  vals = if val.is_a?(Hash)
           val = val[val.keys.last]
           return val.values.flatten if val.is_a?(Hash) # for Hash fetch the last one
           return val.flatten # for Array
         else
           [val]
         end

  vals.each do |each|
     p each
  end
end

这可行。 但是,如果您有任何其他好的解决方案,请将其发布:)