如题,怎么判断一个数组对象是一维数组、二维数组,还是其他几维数组? 多谢!
module ObjectExtension
refine Object do
def dimension
self.class == Array ? 1 + self[0].dimension : 0
end
end
end
using ObjectExtension
puts [1].dimension # 1
puts [[1], [2]].dimension # 2
puts [[[1,2],[2,3]],[[3,4],[5]]].dimension # 3
puts 'a'.dimension # 0
def dimension(array)
return 0 if array.class != Array || array.empty?
max = 0
array.each do |a|
t = dimension(a)
max = [max, t].max
end
max + 1
end
p dimension([[[1,2],[2,[3,[4]]]],[[3,4],[5]]]) # 5
class Array
def dimension
select { |e| e.is_a?(Array) }.map(&:dimension).max.to_i + 1
end
end
官方的flatten!
,妥妥滴。
为什么要用递归呢,ruby 的递归耗 cpu 的,能不用就不用。就性能来说,递归更适合用那些静态语言
➜ ~ pry
[1] pry(main)> a = [1, [2], [1, [2, [3]]], 'l', 'dota']
=> [1, [2], [1, [2, [3]]], "l", "dota"]
[2] pry(main)> i = 1
=> 1
[3] pry(main)> while a.flatten!(1)
[3] pry(main)* i += 1
[3] pry(main)* end
=> nil
[4] pry(main)> puts i
4
=> nil
[5] pry(main)> a
=> [1, 2, 1, 2, 3, "l", "dota"]
[6] pry(main)> b = %w( i love lol, dota go die)
=> ["i", "love", "lol,", "dota", "go", "die"]
[7] pry(main)> j = 1
=> 1
[8] pry(main)> while b.flatten!(1)
[8] pry(main)* j += 1
[8] pry(main)* end
=> nil
[9] pry(main)> puts j
1
=> nil
[10] pry(main)>