How to get similar elements from a array in Ruby.

Hi all,

How to get similar elements from a array in Ruby.

eg : [[1,2],[11,2],[23,89]]

when i give input 1 i should get all arrays like [[1,2],[11,2]]

Thanks in advance..

lekha p. wrote:

How to get similar elements from a array in Ruby.

eg : [[1,2],[11,2],[23,89]]

when i give input 1 i should get all arrays like [[1,2],[11,2]]

That stretches the concept of "similar", since 11 contains 1 mainly
when printed as a string, but it's stored there as a number.

Anyway, it seems to me that the fundamental concept of what you're
after, is how to get the element of an array that fit some criterion,
like all the sub-arrays with three elements or that add up to a
multiple of seven or whatever. You can use Array#select, plus a block
that will evaluate to true for only the elements you want. For
example, to get the ones where the second element is odd, you could
do:

  my_array.select { |sub_array| sub_array[1].odd? }

How to change the block so that it reflects your criteria above, is
left as an exercise for the reader. It's easy, but I want to make
sure you have some actual challenge. :slight_smile:

-Dave

Is [11,2] returned because it has a one in the lowest position, in the
highest position, in any position? Or because 1 + 1 is 2?

IOW, define *exactly* what you mean by "similar". Write a test that
expresses that.

Yeh im looking for that, some method which gives element for my string
matching, :slight_smile:

Yes, it is actually like below. yeh it has a one in the string.

eg : [['1','2'],['11','2'],['23','89']]

Then Dave's answer is the way to go. With the appropriate test of course.

Colin

``

is this fit for your purpose ?

def my_select(array,str)
array.select{ |sub_array| %r(#{str})=~ sub_array.join}
end

def another_select(array,str)
array.select{ |sub_array| %r(#{str})=~ sub_array.first.to_s}
end

my_array = [[1,2],[11,2],[23,89]]
while str = gets
p my_select(my_array,str.chomp)
p another_select(my_array,str.chomp)
end