Code tagged with array

Create a Hash from an Array object

Posted by mqj 8 days ago
>> a = [1,2,3,4,5,6,7,8,9,10]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>> Hash[ *a ]
=> {5=>6, 1=>2, 7=>8, 3=>4, 9=>10}
>> 
?>   b = [ [1,2], [3,4], 5, 6, 7, 8, 9, 10 ]
=> [[1, 2], [3, 4], 5, 6, 7, 8, 9, 10]
>> Hash[ *b ]
=> {5=>6, [1, 2]=>[3, 4], 7=>8, 9=>10}
Language Ruby / Tagged with hash, array

Create a Hash from two Array objects

# Requires Ruby 1.8.7 or higher.

>> keys = [1,2,[3,4]]
=> [1, 2, [3, 4]]
>> values = ['a','b',['c','d']]
=> ["a", "b", ["c", "d"]]
>> Hash[ * keys.zip(values).flatten(1) ]
=> {1=>;"a", [3, 4]=>["c", "d"], 2=>"b"}
Language Ruby / Tagged with hash, array, arrays, zip

Paginating an Array/Enumerable

  def paginate_collection(collection, options = {})
    default_options = {:per_page => 10, :page => 1}
    options = default_options.merge options

    pages = Paginator.new self, collection.size, options[:per_page], options[:page]
    first = pages.current.offset
    last = [first + options[:per_page], collection.size].min
    slice = collection[first...last]
    return [pages, slice]
  end
Language Ruby / Tagged with pagination, array, enumerable