[英]Recursively access the last values from array within hash
The input may come something from string
or array
within hash
. 输入可能来自hash
string
或array
。
However, 然而,
Hash
could be recursive. Hash
可以是递归的。 Array
could have multiple values. Array
可以有多个值。 Example; 例;
# 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"]}}
I'd love to render the string or each of the last values within array. 我想渲染字符串或数组中的每个最后一个值。
# 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"
def leaves(input, acc = [])
if input.is_a?(Enumerable)
input.each_with_object(acc) { |e, acc| leaves([*e].last, acc) }
else
acc << input
end
end
leaves({ 1=>{2=>[3,4], 3=>[5,[6, 7]] }})
#⇒ [3, 4, 5, 7]
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
This could work. 这可能有效。 However if you have any other good solutions, please post it up :) 但是,如果您还有其他好的解决方案,请张贴它:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.