Scroll to top

Playing with data structures in Ruby


Ali - November 17, 2011 - 1 comment

Sorting

I’ve been trying to sort a mixed array in Ruby the shortest way. Each element of the array by itself is a mixed array of a number and and a hash:

a = [
  [0, {:a=>"31", :b=>"21"}],
  [1, {:a=>"32", :b=>"11"}],
  [1, {:a=>"25", :b=>"19"}],
  [0, {:a=>"12", :b=>"10"}]
]
 
#sort by first item of each row (number)
a.sort{|x,y| x[0]  y[0]}
 
#sort by the first item in the hash
a.sort{|x,y| x[1][:a]  y[1][:a]}

Note: I initially posted this as a question on Stackoverflow and got different but correct answers.

Finding common elements

To find common elements between a number of arrays, simply add them to a hash and use the & operator, which creates a new array from two existing arrays containing only elements that are common to both arrays, omitting duplication. (See Techtopia)

a1 = [[1, 2, 3], [1, 2, 2], [2, 2, 3], [3, 2, 1]]
a2 = [[1, 2, 1], [1, 2, 2], [2, 2, 4], [3, 2, 1], [1, 2, 3]]
a3 = [[1, 2, 3], [1, 2, 2], [2, 2, 3], [3, 2, 1], [2, 2, 2]]
hash = {i1: a1, i2: a2, i3: a3}
common = hash.values.inject{|x, y| x & y}

What I can do with Ruby in just one line fascinates me.

1 comment

  1. Mitesh

    a1 & a2 & a3 is the better way to do it ruby.

Post a Comment

Your email address will not be published. Required fields are marked *