Module: Enumerable

Included in:
ConfigScript
Defined in:
lib/el4r/el4r-sub.rb,
lib/el4r/el4r-sub.rb,
lib/el4r/el4r-sub.rb

Overview

map_with_index

Instance Method Summary collapse

Instance Method Details

#build_hashObject

Like #map/#collect, but it generates a Hash. The block is expected to return two values: the key and the value for the new hash.

numbers  = (1..3)
squares  = numbers.build_hash { |n| [n, n*n] }   # 1=>1, 2=>4, 3=>9
sq_roots = numbers.build_hash { |n| [n*n, n] }   # 1=>1, 4=>2, 9=>3


738
739
740
741
742
743
744
745
# File 'lib/el4r/el4r-sub.rb', line 738

def build_hash
  result = {}
  self.each do |elt|
    key, value = yield elt
    result[key] = value
  end
  result
end

#map_with_indexObject

Same as Enumerable#map, but the index is yielded as well. See Enumerable#each_with_index.

puts files.map_with_index { |fn, idx| "#{idx}. #{fn}" }
print "Please select a file (0-#{files.size}): "


757
758
759
760
761
762
763
# File 'lib/el4r/el4r-sub.rb', line 757

def map_with_index
  result = []
  self.each_with_index do |elt, idx|
    result << yield(elt, idx)
  end
  result
end

#mapf(message) ⇒ Object

“map function”

enum.mapf(:x)

is short for

enum.map { |elt| elt.x }


724
725
726
# File 'lib/el4r/el4r-sub.rb', line 724

def mapf(message)
  self.map { |elt| elt.send(message) }
end