Forum: Ruby Reflection method name order

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.
Greg W. (Guest)
on 2008-11-26 09:37
Can I depend on .methods returning methods in the order they are written
in the class source code?

I would assume Unit::Test counts on that, and playing around with this
test seems to indicate that order is retained, but not sure if I'm just
getting lucky. (Seems weird that order is retained, yet the names are
dispersed among all the other inherited methods of the class, rather
than grouped at the end or something.)

class Matchers
  def match_first
  end
  def match_second
  end
  def match_another
  end
  def match_last_one
  end
end

x = Matchers.new

matchers = []
x.methods.each do |method_name|
  matchers << method_name if method_name.scan(/^match_/)[0]
end

p matchers
# => ["match_first", "match_second", "match_another", "match_last_one"]

Thx

-- gw
Stefano C. (Guest)
on 2008-11-26 09:47
(Received via mailing list)
Alle Wednesday 26 November 2008, Greg W. ha scritto:
>   def match_first
>
> -- gw
I don't think you can depend on it. Look at this:

class C
 def x;end
 def y;end
 def a;end
 def z;end
end
p C.new.methods.grep(/^\w$/)
#=> ["y", "x", "z", "a"]

This is with ruby 1.8.7 and linux. By the way, why do you think
Test::Unit
relies on the definition order of the methods?

Stefano
This topic is locked and can not be replied to.