TechArena Community

TechArena Community (http://forums.techarena.in/)
-   Software Development (http://forums.techarena.in/software-development/)
-   -   Counting numbers and deleting array (http://forums.techarena.in/software-development/1026360.htm)

SalVatore 25-08-2008 01:45 PM

Counting numbers and deleting array
 
I am trying to delete an element from an array if it exists and count the number of item afterwards

I wrote
Code:

anArray = [1,2,3,4,5,6,7,8,9]
anArray.size
=> 9
anArray.map {|e| e if e != 4}.compact
=> [1, 2, 3, 5, 6, 7, 8, 9]
anArray.map {|e| e if e != 4}.compact.size
=> 8

Is ther a better way to do it... it it's enough ? (learning always how to write better code..)

Thanks

Praetor 25-08-2008 01:47 PM

Quote:

Originally Posted by SalVatore (Post 3939124)
I am trying to delete an element from an array if it exists and count the number of item afterwards

How about using Array#delete_if?

Modifier 25-08-2008 01:48 PM

Array#delete works also with no need for a block (i.e. you're only checking for equality)

anArray = [1,2,3,4,5,6]
p anArray.delete(4)
p anArray.size


All times are GMT +5.5. The time now is 02:22 PM.