Convert PHP code into Ruby!
RSS icon Email icon Home icon
  • array_chunk

    Posted on October 17th, 2009 RubyLove 2 comments

    The array_chunk() function in PHP splits an array into multiple smaller arrays (array chunks).

    PHP

    $langs = array('php', 'ruby', 'java', 'perl', 'csharp');
    $my_size = 2;
    var_dump( array_chunk($langs, $my_size) );
     
    /*
    Array (
        [0] => Array
            (
                [0] => php
                [1] => ruby
            )
     
        [1] => Array
            (
                [0] => java
                [1] => perl
            )
     
        [2] => Array
            (
                [0] => csharp
            )
     
    ) )
    */

    Ruby

    def array_chunk(full_array, size)
            number_of_chunks = (full_array.length/size.to_f).ceil;
            chunks = (1..number_of_chunks).collect { [] }
                while full_array.any?
                  chunks.each do |a_chunk|
                    a_chunk << full_array.shift if full_array.any?
                  end
                end
            chunks
    end
     
    langs = ["php", "ruby", "java", "perl", "csharp"]
    my_size = 2
    p array_chunk(langs, my_size)
     
    # => [["php", "perl"], ["ruby", "csharp"], ["java"]]
     

    2 responses to “array_chunk”

    1. errrmmm what about Array#each_slice, or Array#slice ??

      also, the method you implemented in ruby doesn’t have the same behaviour

      >> ["php", "ruby", "java", "perl", "csharp"].each_slice(2) do |chunk| puts chunk.inspect end
      ["php", "ruby"]
      ["java", "perl"]
      ["csharp"]

      ————————
      >> langs.slice!(0, 2)
      => ["php", "ruby"]
      >> langs.slice!(0, 2)
      => ["java", "perl"]
      >> langs.slice!(0, 2)
      => ["csharp"]

    2. please replace this implementation,
      it is overcomplicated and inefficient,
      and there is “each_slice”.

    Leave a reply