Class: Sinatra::AssetPack::HashArray

Inherits:
Array
  • Object
show all
Defined in:
lib/sinatra/assetpack/hasharray.rb

Overview

Class: HashArray A stopgap solution to Ruby 1.8’s lack of ordered hashes.

A HashArray, for all intents and purposes, acts like an array. However, the common stuff are overloaded to work with hashes.

## Basic usage

#### Creating You can create a HashArray by passing it an array.

dict = HashArray.new([
  { :good_morning => "Bonjour" },
  { :goodbye      => "Au revoir" },
  { :good_evening => "Bon nuit" }
])

#### Converting You may also use it like so:

letters = [ { :a => "Aye"}, { :b => "Bee" } ].to_hash_array

#### Iterating Now you can use the typical enumerator functions:

dict.each do |(key, value)|
  puts "#{key} is #{value}"
end

#=> :good_morning is "Bonjour"
#   :goodbye is "Au revoir"
#   :good_evening is "Bon nuit"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.[](*arr) ⇒ Object



37
38
39
# File 'lib/sinatra/assetpack/hasharray.rb', line 37

def self.[](*arr)
  new arr.each_slice(2).map { |(k, v)| Hash[k, v] }
end

Instance Method Details

#keysObject



51
52
53
# File 'lib/sinatra/assetpack/hasharray.rb', line 51

def keys
  inject([]) { |a, (k, v)| a << k; a }
end

#to_hashObject

Returns everything as a hash.



47
48
49
# File 'lib/sinatra/assetpack/hasharray.rb', line 47

def to_hash
  inject({}) { |hash, (k, v)| hash[k] = v; hash }
end

#valuesObject

Works like Hash#values.



42
43
44
# File 'lib/sinatra/assetpack/hasharray.rb', line 42

def values
  inject([]) { |a, (k, v)| a << v; a }
end