开发者

How to split one level array to many arrays in Ruby 1.9.2

I have an array like this:

[234, 235 , 343, 445]

I want to convert it to look like this

[[234],[235],[343],[445]]

Is there core library function in ruby 1.9.2 could help me to do this fast? and if not is there a fast way?


I did a small tests

def test1
  array = []
  10000000.times do
    array << rand(1000000)
  end
  time = Time.now
  array.permutation(1).to_a
  puts "test1 (permutation) ---> Time = #{Time.now - time}"
end

def test2
  array = []
  10000000.times do
    array << rand(1000000)
  end
  time = Time.now
  array.zip()
  puts "test2 (zip开发者_StackOverflow社区)---> Time = #{Time.now - time}"
end

def test3
  array = []
  10000000.times do
    array << rand(1000000)
  end
  time = Time.now
  array.map { |a| [a] }
  puts "test3 (map) ---> Time = #{Time.now - time}"
end

test1 #test1 (permutation) ---> Time = 2.235128
test2 #test2 (zip)         ---> Time = 1.537088
test3 #test3 (map)         ---> Time = 2.230127


I dont think there is a core function to do that, but there is a fast way:

irb(main):001:0> [234, 235 , 343, 445].map { |a| [a] }
=> [[234], [235], [343], [445]]


Array#zip (with no arguments) should do it as well, though the map is probably more straightforward:

telemachus $ irb
>> new = [234, 235 , 343, 445].zip() # The () is optional, .zip would work fine
=> [[234], [235], [343], [445]]


In 1.9.2 you can do:

[234, 235 , 343, 445].permutation(1).to_a


I don't think you're going to get all that fast with this task. As your benchmark suggests, zip is the fastest method (that you tested at least). However, this still needs to create a massive amount of Array objects, and that's just going to take time. If you need this to go faster, maybe you should look at how the data is used. Without more information about that, all I have to say is: Why does it need an array in this format?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜