Wednesday, October 14, 2009

Ruby on Rails : Array : Remove item

Arrays are ordered, integer-indexed collections of any object. Array indexing starts at 0, as in C or Java. A negative index is assumed to be relative to the end of the array—that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.

Example:
<%
@number = "1,2,3,4,5,6"
@split = @number.split(",")

str = Array.new
count = 0

for i in 0...@split.length
   if ( @split[i].to_i != 4 )
     str[count] = @split[i]
     count += 1
   else
   end
end
result = str*","
%>
<%= result %>

Output:
1,2,3,5,6

Class Library : http://corelib.rubyonrails.org/classes/Array.html

2 comments:

  1. Instead of this, we can use another method as follows :
    result =[]
    result = @number.delete("4,")

    ReplyDelete
    Replies
    1. Shorter steps! Awesome! Thanks for sharing.

      Delete