'How to call a methods in multiple classes in ruby
class One
class Two
class Three
def name
Faker::Name.name
end
end
def workflow
Three.new
end
end
def event
Two.new
end
def id
Faker::Number.number(4).to_i
end
end
I am new to ruby. Can someone help me, how to call all these methods in ruby?
Solution 1:[1]
Is this what you looking for?
one = One.new
two = One::Two.new
three = One::Two::Three.new
three.name
# => "Mr. Dillon Jacobson"
two.workflow
# => #<One::Two::Three:0x000055b2d9d70be0>
one.event
# => #<One::Two:0x000055b2df4160d0>
one.id
# => 6579413068
Solution 2:[2]
Pretty simple to do with instance_methods(false) that will give us all the defined instance methods of a class. We can then just push all the nested objs into an array and iterate over them. I'm not too sure on how to get all nested classes. You can however do that with Module.nesting
def call_all_methods(obj)
obj.class.instance_methods(false).each do |m|
obj.public_send(m)
end
end
[
One.new,
One::Two.new,
One::Two::Three.new
].each do |obj|
call_all_methods(obj)
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aparichith |
| Solution 2 | sneakyfishies |
