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…
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.
-Dave
–
Dave A., consulting software developer of Codosaur.us,
PullRequestRoulette.com, Blog.Codosaur.us, and Dare2XL.com.
AVAILABLE FOR CONTRACTS (remotely or in Northern Virginia).
On Mon, Feb 2, 2015 at 7:08 AM, lekha p. [email protected] 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]]
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.
–
Hassan S. ------------------------ [email protected]
twitter: @hassan
Yeh im looking for that, some method which gives element for my string
matching,
Yes, it is actually like below. yeh it has a one in the string.
eg : [[‘1’,‘2’],[‘11’,‘2’],[‘23’,‘89’]]
Result
[‘1’,‘2’],[‘11’,‘2’]
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
On 2 February 2015 at 15:38, lekha p. [email protected] wrote:
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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs