2023-05-25 17:47:19 +02:00
|
|
|
# Lösung: Methoden dynamisch aufrufen
|
2023-05-23 09:19:31 +02:00
|
|
|
|
2023-05-25 17:47:19 +02:00
|
|
|
<div style="border: 1px solid grey;"><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br></div>```ruby
|
|
|
|
def crazy_caller(obj)
|
|
|
|
# Methoden suchen
|
|
|
|
obj.methods.each do |m|
|
|
|
|
# m enthält ein Symbol mit dem Namen der Methode,
|
|
|
|
# wir wollen aber das Methoden-Objekt
|
|
|
|
method = obj.method(m)
|
2023-05-23 09:19:31 +02:00
|
|
|
|
2023-05-25 17:47:19 +02:00
|
|
|
begin
|
|
|
|
# Methode aufrufen, wenn sie keinen Parameter hat
|
|
|
|
method.call {} if method.arity == 0
|
|
|
|
rescue
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2023-05-23 09:19:31 +02:00
|
|
|
|
2023-05-25 17:47:19 +02:00
|
|
|
class Test
|
|
|
|
def m1; puts 'm1'; end
|
|
|
|
def m2; puts 'm2'; end
|
|
|
|
def m3(a); puts 'm3'; end
|
|
|
|
def m4(a, b); puts 'm4'; end
|
2023-05-23 09:19:31 +02:00
|
|
|
end
|
|
|
|
|
2023-05-25 17:47:19 +02:00
|
|
|
crazy_caller(Test.new)
|
2023-05-23 09:19:31 +02:00
|
|
|
```
|