Ruby如何从数组中删除[]括号?

时间:2012-01-16 01:04:56

标签: ruby

我有这个数组:

[[16], [14], [13], [17], [18], [15, 16], [15, 14], [15, 13], [15, 17], [15, 18], [16, 14], [16, 13], [16, 17], [16, 18], [14, 13], [14, 17], [14, 18], [13, 17], [13, 18], [17, 18], [15, 16, 14], [15, 16, 13], [15, 16, 17], [15, 16, 18], [15, 14, 13], [15, 14, 17], [15, 14, 18], [15, 13, 17], [15, 13, 18], [15, 17, 18], [16, 14, 13], [16, 14, 17], [16, 14, 18], [16, 13, 17], [16, 13, 18], [16, 17, 18], [14, 13, 17], [14, 13, 18], [14, 17, 18]]

如何删除一些数组括号[],以便数组如下:

[16, 14, 13, 17, 18, [15, 16], ..., [14, 13, 18], [14, 17, 18]]

3 个答案:

答案 0 :(得分:3)

new_arr = arr.collect { |a| a.size == 1 ? a[0] : a }

或者,就地:

arr.collect! { |a| a.size == 1 ? a[0] : a }

非信徒的输出:

[1] pry(main)> arr = [[16], [14], [15, 16], [15, 14], [15, 16, 17], [15, 16, 18]]
=> [[16], [14], [15, 16], [15, 14], [15, 16, 17], [15, 16, 18]]
[3] pry(main)> new_arr = arr.collect { |a| a.size == 1 ? a[0] : a }
=> [16, 14, [15, 16], [15, 14], [15, 16, 17], [15, 16, 18]]
# Note that arr is unchanged at this point.
[5] pry(main)> arr.collect! { |a| a.size == 1 ? a[0] : a }
=> [16, 14, [15, 16], [15, 14], [15, 16, 17], [15, 16, 18]]
[6] pry(main)> arr
=> [16, 14, [15, 16], [15, 14], [15, 16, 17], [15, 16, 18]]

答案 1 :(得分:1)

这不是很优雅,但你会得到你想要的东西:)。

b = [[16], [14], [13], [17], [18], [15, 16], [15, 14], [15, 13], [15, 17], [15, 18], [16, 14], [16, 13], [16, 17], [16, 18], [14, 13], [14, 17], [14, 18], [13, 17], [13, 18], [17, 18], [15, 16, 14], [15, 16, 13], [15, 16, 17], [15, 16, 18], [15, 14, 13], [15, 14, 17], [15, 14, 18], [15, 13, 17], [15, 13, 18], [15, 17, 18], [16, 14, 13], [16, 14, 17], [16, 14, 18], [16, 13, 17], [16, 13, 18], [16, 17, 18], [14, 13, 17], [14, 13, 18], [14, 17, 18]]

b.collect { |c| c.count() ==  1 ? c[0] : c }

答案 2 :(得分:0)

这个问题有点不清楚。看来你有一个阵列数组,是吗?如果是这样,你可以做这样的事情

count = 0
array.each { |x|
  if x.is_a?(Array)
    if x.length == 1
      array[count] = x[0]
    end
  end
  count = count + 1
}

这可以做得更漂亮,但它应该做你想要的,如果你想要的是交换单个元素数组只是一个整数。我不完全确定你是否可以在Ruby中执行此操作,但是 - 有一个数组是整数和数组的数组 - 但我认为你可以(你不能在Java中做这样的事情)。