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. :-)
-Dave
--
Dave Aronson, consulting software developer of Codosaur.us,
PullRequestRoulette.com, Blog.Codosaur.us, and Dare2XL.com.
AVAILABLE FOR CONTRACTS (remotely or in Northern Virginia).
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/CAHxKQijd10yBU9KO3GPc3h0Y-5r_W9%3DX3VU6pojhFJeHxK__SA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment