Results 1 to 3 of 3

Thread: Counting numbers and deleting array

  1. #1
    Join Date
    May 2008
    Posts
    2,680

    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

  2. #2
    Join Date
    Apr 2008
    Posts
    1,948
    Quote Originally Posted by SalVatore View Post
    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?

  3. #3
    Join Date
    Jan 2008
    Posts
    1,521
    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

Similar Threads

  1. How to change negative numbers to positive numbers in Excel
    By Shaina Na in forum Microsoft Project
    Replies: 3
    Last Post: 08-01-2012, 05:35 PM
  2. Need C program code to count numbers of negative & positive numbers
    By Sarfaraj Khan in forum Software Development
    Replies: 5
    Last Post: 16-01-2010, 02:00 PM
  3. Want an array of Random numbers
    By InterNetWorKed in forum Software Development
    Replies: 4
    Last Post: 03-11-2009, 02:17 PM
  4. Loop counting odd and even numbers
    By Allan.d in forum Software Development
    Replies: 3
    Last Post: 23-10-2009, 11:40 AM
  5. SQL Query for Searching Missing Numbers from Sequence of Numbers
    By Bhagwandas in forum Software Development
    Replies: 3
    Last Post: 18-02-2009, 01:47 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,750,373,960.46768 seconds with 16 queries