メソッド名一覧の表示
Posted feedbacks - Ruby
1 2 3 4 5 6 7 8 9 | class Foo
private; def test_foo() puts("test_foo_private") end
public; def test_foo2() puts("test_foo_public") end
protected; def test_fuga() puts("test_fuga") end
public; def public_foo() puts("public_foo") end
end
obj = Foo.new
["methods","private_methods"].collect{|m| obj.send(m).grep(/^test_/)}.flatten.each{|m| obj.instance_eval m}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Object
def call_test(prvt = false)
test_methods = self.methods.grep(/\Atest_/)
test_methods += self.private_methods.grep(/\Atest_/) if prvt
test_methods.each{|method|
yield method, self.__send__(method)
}
end
end
if $0 == __FILE__
class Sample
def test_a
true
end
end
o = Sample.new
o.call_test{|m, r|
puts "#{m} #{r}"
}
end
|
誰でも思いつく単純な回答
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class Target
def test_foo
p "foo"
end
def test_bar
p "bar"
end
def test_baz
p "baz"
end
def not_test
p "not test!!"
end
end
#=> nil
target = Target.new
#=> #<Target:0x107d1d0>
target.methods.grep(/^test_.*$/).each {|i| target.__send__ i }
"baz"
"foo"
"bar"
#=> ["test_baz", "test_foo", "test_bar"]
|
Privateメソッドも実行するために.
1 2 3 4 5 6 7 | STR = 'test_'
module ExeTest_
def exe_test_(x); eval(x) end
end
target = Object.new
target.extend ExeTest_
target.methods.grep(/\A#{STR}/).each{|x| target.exe_test_(x)}
|



にしお
#3388()
Rating1/1=1.00
「ある与えられたオブジェクトtargetのメソッドのうち、 "test_"で始まるものをすべて呼びだす」というコードを書いてください。 引数に関しては都合のいいように仮定して構いません(全部0個、など)。
メソッドという概念がない言語の場合は、 「複数の関数への参照を持っているようなオブジェクト(たとえばパッケージとかモジュールとか)から"test_"で始まる関数をすべて呼び出す」と読み替えても構いません。
[ reply ]