【问题标题】:Functional unwrapping of nested array嵌套数组的功能展开
【发布时间】:2010-06-30 20:33:44
【问题描述】:

给定一个包含其他嵌套数组的数组,我想创建一个仅包含第一个数组中的元素的数组。例如 [["1", "2"], "3", [["4"]]] 应该评估为 ["1", "2", "3", "4"]。

我设法制作了一个有效的方法:

@@unwrapped_array = []  
def unwrap_nested_array(array)  
  if array.respond_to?('each')  
    array.each { |elem| unwrap_nested_array(elem) }  
  else  
    @@unwrapped_array.push array  
  end  
end

但我一直无法弄清楚如何消除@@unwrapped_array 变量。

【问题讨论】:

    标签: ruby functional-programming ruby-1.9


    【解决方案1】:
    [["1", "2"], "3", [["4"]]].flatten
    # => ["1", "2", "3", "4"]
    

    【讨论】:

    • 谢谢!我知道有一个简单的答案,只是不是那么容易:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 2017-03-03
    • 2018-10-07
    • 2021-12-11
    • 2018-11-04
    • 1970-01-01
    相关资源
    最近更新 更多