Sha256: 2826a558ef524cc25e9fc0ccb731c1979a62478d08e20031b1b0a48673490934

Contents?: true

Size: 1.14 KB

Versions: 1

Compression:

Stored size: 1.14 KB

Contents

class Array

  def to_param
    self.collect { |element| element.respond_to?(:to_param) ? element.to_param : element }
  end

  def show_name
    first.titleize
  end

  # Key should be unique, or latest element with that key will override previous ones.
  def hash_by(key = nil, method = nil, &block)
    self.inject({}) do |h, element|
      if key
        h[element.send(key)] = if block_given?
          yield(element)
        elsif method
          element.send(method)
        else
          element
        end
      else # key is block and value is element
        h[yield(element)] = element
      end
      h
    end
  end

  def hash_by_id(method = nil, &block)
    hash_by(:id, method, &block)
  end

  def intersects?(other)
    self.any?{|i| other.include?(i)}
  end

  # Same effect as Array.wrap(object).first
  # but no need to create new object in case of non-array
  def self.first(object)
    return object.first if object.is_a?(Array)
    object
  end

  # Same effect as Array.wrap(object).last
  # but no need to create new object in case of non-array
  def self.last(object)
    return object.last if object.is_a?(Array)
    object
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ruby_core_extensions-0.0.1 lib/ruby_core_extensions/array.rb