假设我有以下内容:
nested_object = [0, 1, 2, {foo: 'bar'}]
在搜索更深的嵌套对象时,如何使用 dig 来选择数组的最后一个元素?
最佳答案
任何 dig 方法参数中的负值整数从数组的末尾开始并向开头移动。所以 -1
选择数组的最后一个元素,-2
选择倒数第二个元素,依此类推。所以,在你的情况下:
target = nested_object.dig(-1, :foo)
将选择数组的最后一个元素并从那里继续。
关于arrays - 能否使用 dig 方法获取数组的最后一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40364210/