Forum: Ruby Reflection method name order

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
4a9cd711ccb80f1ab3ce17450c2857e4?d=identicon&s=25 Greg Willits (-gw-)
on 2008-11-26 08: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
  def match_second
  def match_another
  def match_last_one

x =

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

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


-- gw
C40020a47c6b625af6422b5b1302abaf?d=identicon&s=25 Stefano Crocco (crocco)
on 2008-11-26 08:47
(Received via mailing list)
Alle Wednesday 26 November 2008, Greg Willits 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
#=> ["y", "x", "z", "a"]

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

This topic is locked and can not be replied to.