ruby - Ruby 中的嵌套数组和字符串

标签 ruby

我正在尝试找出嵌套数组,尤其是多维类型的数组。我已经阅读了两篇关于它们的文章,并且在迭代检查字符串时被绊倒了。

# Array - 
more_nested_array = [["hello", ["world", "new york"]], ["love", "ruby"]]

# Iteration-
more_nested_array.each do |element|
 element.each do |inner_element|
    if inner_element.is_a?(Array)
      inner_element.each do |third_layer_element|
     end
   end
  end
end

所以它使用 if 语句,因为据说在某些迭代中有字符串。这种对字符串的引用让我感到困惑,因为它看起来只是一堆数组。有人可以解释一下吗?

最佳答案

NoMethodError 否则

需要进行检查,因为循环是针对此给定树(或嵌套数组,如果您愿意)进行硬编码的。

取消勾选:

more_nested_array = [["hello", ["world", "new york"]], ["love", "ruby"]]

# Iteration-
more_nested_array.each do |element|
  element.each do |inner_element|
    inner_element.each do |third_layer_element|
      puts third_layer_element
    end
  end
end

输出:

undefined method `each' for "hello":String (NoMethodError)

因为并非每个 inner_element 都是数组或响应 each

递归版本

对于这种结构,最好编写递归方法来解析树,而不是对树深度和节点类进行硬编码。

more_nested_array = [["hello", ["world", "new york"]], ["love", "ruby"]]

def parse_tree(node, current_depth = 0)
  if node.respond_to?(:each)
    node.each do |child|
      parse_tree(child, current_depth + 1)
    end
  else
    puts "Found #{node.inspect} at depth #{current_depth}"
  end
end

parse_tree(more_nested_array)

输出:

Found "hello" at depth 2
Found "world" at depth 3
Found "new york" at depth 3
Found "love" at depth 2
Found "ruby" at depth 2

关于ruby - Ruby 中的嵌套数组和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44782986/

相关文章:

ruby-on-rails - 等同于 foo_ids 的 find_each?

ruby - 如何使用 vagrant 1.7.2 在 Windows 7 x64 上 vagrant up(使用 puphpet)?

ruby - 进入域后如何配置静默登录Redmine?

ruby-on-rails - Ruby:给定日期找到下一个第二或第四个星期二

ruby-on-rails - Rails 5 仅当属性当前为 nil 时才更新属性

ruby-on-rails - Ruby On Rails - 重用错误消息部分 View

ruby - 多个变量赋值是同时完成的吗?

mysql - 我想将整个 MySQL 表作为数组读入 ruby​​。我正在使用事件记录

ruby-on-rails - Rspec allow_any_instance_of 返回实例 ID

ruby - Ruby中 block 的使用顺序是什么