Class: OrderedHash

Inherits:
Hash show all
Includes:
ForHashes
Defined in:
lib/shorthand.rb,
lib/shorthand.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ForHashes

#clean, #hmap, #map_vals, #map_vals!, #stable_compact, #to_sig

Constructor Details

#initialize(*args, &block) ⇒ OrderedHash

Returns a new instance of OrderedHash.



353
# File 'lib/shorthand.rb', line 353

def initialize(*args, &block) super; @keys = [] end

Class Method Details

.[](*args) ⇒ Object



343
344
345
346
347
348
349
350
351
# File 'lib/shorthand.rb', line 343

def self.[](*args)
  ordered_hash = new
  args.each_with_index { |val,ind|
    # Only every second value is a key.
    next if ind % 2 != 0
    ordered_hash[val] = args[ind + 1]
  }
  ordered_hash
end

Instance Method Details

#[]=(key, value) ⇒ Object



355
# File 'lib/shorthand.rb', line 355

def []=(key, value) @keys << key if !has_key?(key); super end

#clearObject



375
# File 'lib/shorthand.rb', line 375

def clear; super; @keys.clear; self end

#delete(key) ⇒ Object



356
357
358
359
360
361
362
363
# File 'lib/shorthand.rb', line 356

def delete(key)
  $stderr.puts "Deleting key #{key}"
  if has_key? key
    index = @keys.index(key)
    @keys.delete_at index
  end
  super
end

#delete_ifObject



364
# File 'lib/shorthand.rb', line 364

def delete_if() super; sync_keys!; self end

#eachObject Also known as: each_pair



373
# File 'lib/shorthand.rb', line 373

def each; @keys.each {|key| yield [key, self[key]]} end

#each_keyObject



371
# File 'lib/shorthand.rb', line 371

def each_key; @keys.each { |key| yield key } end

#each_valueObject



372
# File 'lib/shorthand.rb', line 372

def each_value; @keys.each { |key| yield self[key]} end

#initialize_copy(other) ⇒ Object



354
# File 'lib/shorthand.rb', line 354

def initialize_copy(other) super; @keys = other.keys end

#inspectObject



379
# File 'lib/shorthand.rb', line 379

def inspect; "#<OrderedHash #{super}>" end

#keysObject



367
# File 'lib/shorthand.rb', line 367

def keys; @keys.dup end

#merge(other_hash) ⇒ Object



378
# File 'lib/shorthand.rb', line 378

def merge(other_hash) dup.merge!(other_hash) end

#merge!(other_hash) ⇒ Object



377
# File 'lib/shorthand.rb', line 377

def merge!(other_hash) other_hash.each {|k,v| self[k] = v }; self end

#reject(&block) ⇒ Object



366
# File 'lib/shorthand.rb', line 366

def reject(&block) dup.reject!(&block) end

#reject!Object



365
# File 'lib/shorthand.rb', line 365

def reject!; super; sync_keys!; self end

#shiftObject



376
# File 'lib/shorthand.rb', line 376

def shift; k = @keys.first; v = delete(k) [k, v] end

#to_aObject



370
# File 'lib/shorthand.rb', line 370

def to_a; @keys.map { |key| [ key, self[key] ] } end

#to_hashObject



369
# File 'lib/shorthand.rb', line 369

def to_hash; self end

#valuesObject



368
# File 'lib/shorthand.rb', line 368

def values; @keys.collect { |key| self[key] } end