Showing posts with label Array. Show all posts
Showing posts with label Array. Show all posts

Thursday, June 10, 2010

Ruby. Array.size by conditions

class Array
    def size(&closure)
        closure ? inject(0){ |count, elem| (yield elem) ? count + 1 : count } : length
    end
end

array = [1, 2, 3, 4, 5, 6]
puts array.size{ |i| (i & 1).zero? }.inspect

Sunday, May 2, 2010

Find duplicates in an Array with grep

The following example finds duplicates in an array by selecting all array items which have apear more than once.
a = %w(a b a c)
a.uniq.select {|x| a.grep(x).length > 1}
#=> ["a"]

a = %w(a b a c d d d e f g h f)
a.uniq.select {|x| a.grep(x).length > 1}
#=> ["a", "d", "f"]
 
a = %w(a b a c d d d e f g h f)
a.group_by(&:to_s).select{|k,v| v.length > 1}
#=> {"a"=>["a", "a"], "d"=>["d", "d", "d"], "f"=>["f", "f"]}
http://snippets.dzone.com/posts/show/11219

Sunday, August 2, 2009

Interleave two arrays

Assuming the arrays are of equal length this code interleaves the two arrays to create a new array.
a1 = %w(1 2 3 4)
a2 = %w(a b c d)

a3 = (0..a1.length - 1).map {|i| [a1[i], a2[i]]}.flatten
#=> ["1", "a", "2", "b", "3", "c", "4", "d"]

# or
a3 = (0..a1.length - 1).inject([]) {|n, i| n << a1[i] << a2[i]}
#=> ["1", "a", "2", "b", "3", "c", "4", "d"]

# or
a1.each_with_index {|x,i| a2.insert(i*2, a1[i])}
#=> ["1", "a", "2", "b", "3", "c", "4", "d"]

# or
[a1, a2].transpose.flatten
#=> ["1", "a", "2", "b", "3", "c", "4", "d"]

# or
a1.zip(a2).flatten
#=> ["1", "a", "2", "b", "3", "c", "4", "d"]

http://snippets.dzone.com/posts/show/7652