Раздел «Язык Ruby».CoreExt:

Примеры полезных расширений стандартных классов

class Array
  def to_hash(fieldnames)
    h = {}
    fieldnames.each_with_index{|name, i| h[name] = self[i]}
    h.delete(nil)
    h
  end

  def max_by(&block)
    if self
      self.inject(self.first){|a, x|
        if yield(x) > yield(a)
          x
        else
          a
        end
      }
    end
  end

  def last_n(n)
    return [] if size == 0
    i = [self.size, n].min
    return self[-i..-1]
  end
end

class Hash
  def first
    res=[nil,nil]
    self.each do |k,v|
      res = [k,v]
      break
    end
    return res
  end

  def key_with_max_value
    k_m,v_max = self.first
    self.each do |k,v|
      k_m,v_m = k,v if v > v_m
    end
    return [k_m,v_m]
  end

  def symbolize_keys
    self.each {|k,v|
      self[k.to_sym] = self.delete(k) unless k.is_a?(Symbol)
    }
    self
  end

  def keys_and_values_to_s
    self.each {|k,v|
      (self.delete(k) and next) if (v.nil? or k.nil?)
      self[k.to_s] = self.delete(k).to_s unless (k.is_a?(String) && v.is_a?(String))
    }
  end
end

class String
  def strip_nonalpha!
    self.gsub!(/[^\s\w_абвгдежзййклмнопСТУФХЦЧЩЬЫЫЭЮЯ]/u,'')
    self
  end

  def fingerprint
    s = self.dup
    s.gsub!(/\b\s*and\s*\b/i,'&')
    s.gsub!(/[-,\.;:|\/\\]/i, ' ')
    s.gsub!(/\s+/,' ')
    s.downcase!
    s
  end

  def similarity(str)
    s1 = self.dup.fingerprint
    s2 = str.fingerprint
    s1,s2 = s2,s1 if s1.size > s2.size
    s1s = s1.size
    s2s = s2.size
    b1 = b2 = 0

    # find common prefix
    while s1[b1] == s2[b1] && !s1[b1].nil?
      b1+=1
    end
    return 1.0 if s1s == s2s && b1==s1s
    return s1s.to_f/s2s if b1 == s1s
    v1 = s1s
    v2 = s2s
    hits = b2 = b1
    # and common suffix
    while s1[v1] == s2[v2]
      v1 -= 1
      v2 -= 1
      hits += 1
    end
    while b1 < v1
      (b1 += 1 and b2 += 1 and hits += 1 and next) if s1[b1] == s2[b2]
      (b2 += 1 and next) if s2[b2 + 1] == s1[b1]
      (b1 += 1 and next) if s2[b2] == s1[b1+1]
      if v1 - b1 > v2 - b2
        b1,b2,v1,v2,s1,s2 = b2,b1,v2,v1,s2,s1
      end
      b2+=1
    end
    # p [s1s, s2s, missed, v2, b2, s1, s2]
    hits.to_f/[s1s,s2s].max
  end
end

class Module
 private


# require 'set'
class Set
  def first
    f = nil
    each {|x|  f = x;  break; }
    f
  end
end

-- ArtemVoroztsov - 20 Sep 2007