Forum: Ruby REXML::Parent#index does not return nil

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
TAKANO Noriyuki (Guest)
on 2006-02-05 14:40
(Received via mailing list)
Hi all,

This is my first posting to ruby-talk.
I regularly use REXML, appreciating those who are making and
supporting it.  But wishing it (or bug?) would be fixed, I
wonder if this mailing list is an appropriate place to report
a problem I see in REXML.

problem:
REXML::Parent#index(obj) does not return nil but the last index
of children of the parent
when the argument is not a child of the parent.
In the ruby-doc of REXML::Parent, parent.index method is described:
  index(child)
  Fetches the index of a given child
  @param child the child to get the index of
  @return the index of the child, or nil if the object is
  not a child of this parent.

The cause for not returning nil is obvious in the source code of
Parent#index (REXML 3.1.3)
def index( child )
   count = -1
   @children.find { |i| count += 1 ; i.hash == child.hash }
   count
end

Should it be something like this?
def index( child )
   count = -1
- @children.find { |i| count += 1 ; i.hash == child.hash }
+ @children.find { |i| count += 1 ; i.hash == child.hash } ? count : nil
end

Sample code:
require 'rexml/document'
include REXML
root = Element.new("root")
p [ Element.new("a", root), Element.new("b", root),
Element.new("c")].collect{|ele|
  root.index(ele)
}

alt = Element.new("alt")
def alt.index( child )
  count = -1
  @children.find { |i| count += 1 ; i.hash == child.hash } ? count : nil
end

p [Element.new("a", alt), Element.new("b", alt),
Element.new("c")].collect{|ele|
  alt.index(ele)
}

Regards
  nori

happy, may_not_be = programming.partition{|it| it.is_a? RubyProgramming}
This topic is locked and can not be replied to.