Module: Enumerable

Included in:
Redwood::Thread
Defined in:
lib/sup/util.rb

Instance Method Summary collapse

Instance Method Details

#argfindObject

like find, except returns the value of the block rather than the element itself.



496
497
498
499
500
# File 'lib/sup/util.rb', line 496

def argfind
  ret = nil
  find { |e| ret ||= yield(e) }
  ret || nil # force
end

#argminObject



502
503
504
505
506
507
508
509
510
511
# File 'lib/sup/util.rb', line 502

def argmin
  best, bestval = nil, nil
  each do |e|
    val = yield e
    if bestval.nil? || val < bestval
      best, bestval = e, val
    end
  end
  best
end

#between(startline, endline) ⇒ Object

returns all the entries which are equal to startline up to endline



532
533
534
# File 'lib/sup/util.rb', line 532

def between startline, endline
  select { |l| true if l == startline .. l == endline }
end

#map_to_hashObject



488
489
490
491
492
# File 'lib/sup/util.rb', line 488

def map_to_hash
  ret = {}
  each { |x| ret[x] = yield(x) }
  ret
end

#map_with_indexObject



478
479
480
481
482
# File 'lib/sup/util.rb', line 478

def map_with_index
  ret = []
  each_with_index { |x, i| ret << yield(x, i) }
  ret
end

#max_ofObject



527
528
529
# File 'lib/sup/util.rb', line 527

def max_of
  map { |e| yield e }.max
end

#shared_prefix(caseless = false, exclude = "") ⇒ Object

returns the maximum shared prefix of an array of strings optinally excluding a prefix



515
516
517
518
519
520
521
522
523
524
525
# File 'lib/sup/util.rb', line 515

def shared_prefix caseless=false, exclude=""
  return "" if empty?
  prefix = ""
  (0 ... first.length).each do |i|
    c = (caseless ? first.downcase : first)[i]
    break unless all? { |s| (caseless ? s.downcase : s)[i] == c }
    next if exclude[i] == c
    prefix += first[i].chr
  end
  prefix
end

#sumObject



485
# File 'lib/sup/util.rb', line 485

def sum; inject(0) { |x, y| x + y }; end