Class: Array

Inherits:
Object show all
Defined in:
lib/golly-utils/ruby_ext/deep_dup.rb,
lib/golly-utils/ruby_ext/array_to_hash.rb

Instance Method Summary collapse

Instance Method Details

#deep_dupObject

Creates a copy of the array with deep copies of each element.

See Also:



13
14
15
# File 'lib/golly-utils/ruby_ext/deep_dup.rb', line 13

def deep_dup
  map(&:deep_dup)
end

#to_hash_keyed_by(raise_on_duplicate_keys = true, &key_provider) ⇒ Object

Converts the array to a hash where the values are the array elements and the keys are provided by calling a given block.

Examples:

['m','abc'].to_hash_keyed_by{ |v| v.length }       # => {1 => 'm', 3 => 'abc}


8
9
10
11
12
13
14
15
16
# File 'lib/golly-utils/ruby_ext/array_to_hash.rb', line 8

def to_hash_keyed_by(raise_on_duplicate_keys=true, &key_provider)
  h= {}
  each {|e|
    k= key_provider.call(e)
    raise "Duplicate key: #{k.inspect}" if raise_on_duplicate_keys and h.has_key?(k)
    h[k]= e
  }
  h
end

#to_hash_with_values(value = nil) ⇒ Object

Converts the array to a hash where the keys are the array elements and the values are provided by either calling a given block, or using a fixed, provided argument.

Examples:

[2,5].to_hash_with_values('x')                 # => {2 => 'x', 5 => 'x'}
[2,5].to_hash_with_values{ |k| 'xo' * k }      # => {2 => 'xoxo', 5 => 'xoxoxoxoxo'}


24
25
26
27
28
# File 'lib/golly-utils/ruby_ext/array_to_hash.rb', line 24

def to_hash_with_values(value=nil)
  h= {}
  each {|e| h[e]= block_given? ? yield(e) : value}
  h
end