Reflection method name order

G

Greg Willits

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
 
S

Stefano Crocco

Alle Wednesday 26 November 2008, Greg Willits ha scritto:
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

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top