Issue #6367 has been updated by trans (Thomas Sawyer).


=begin
My methods names for the "_by" methods isn't not very good. This should clarify:

   [1,1,1].all_equal?           #=> true
   [1,1,2].all_equal?           #=> false
   [2,4,6].all_equal?{|x| x*0}  #=> true

   [1,1,2].any_equal?           #=> true
   [1,2,3].any_equal?           #=> false
   [2,3,4].any_equal?(&:even?)  #=> true

   [2,4,6]#all_by?{ |a,b| a % 2 == b % 2 }  #=> true
   [2,3,4]#all_by?{ |a,b| a % 2 == b % 2 }  #=> false

   [2,3,4]#any_by?{ |a,b| a % 2 == b % 2 }  #=> true
   [1,2,3]#any_by?{ |a,b| a % 3 == b % 3 }  #=> false

=end
----------------------------------------
Feature #6367: #same? for Enumerable
https://bugs.ruby-lang.org/issues/6367#change-26310

Author: prijutme4ty (Ilya Vorontsov)
Status: Feedback
Priority: Normal
Assignee: matz (Yukihiro Matsumoto)
Category: 
Target version: 


I realised that I frequently test if all objects in enumerable have the same feature. For example if all words have the same length (but not defined before). So I found particulary useful method Enumerable#same_by? that test this behaviour. I think it can be simply rewritten in C and included to Enumerable core methods.
Simple ruby implementation can be written just in a pair of lines (tests included):

module Enumerable
  def same?(&block)
    return true if empty?
    if block_given?
      first_result = yield(first)
      all?{|el| first_result == yield(el)}
    else
      first_result = first
      all?{|el| first_result == el}
    end
  end
end

require 'test/unit'
class TestEnumerableSame < Test::Unit::TestCase
  def test_same
    assert_equal(true, [1,3,9,7].same?(&:even?))
    assert_equal(true, [4,8,2,2].same?(&:even?))
    assert_equal(false, [1,8,3,2].same?(&:even?))
    
    assert_equal(true, %w{cat dog rat}.same?(&:length))
    assert_equal(false, %w{cat dog rabbit}.same?(&:length))
    
    assert_equal(true, %w{cat cat cat}.same?)
    assert_equal(false, %w{cat dog rat}.same?)
    
    assert_equal(true, [].same?(&:length))
    assert_equal(true, [].same?)
  end
end



-- 
http://bugs.ruby-lang.org/