eeeeeean eeeeeean - 1 month ago 9
Ruby Question

How to stringify method lines?

Can Ruby take a method like this:

def a_few_methods
method1
method2
end


...and create an array like this?

['method1', 'method2']


I'm doing the following, which works, but it seems clunky:

class Foo

def self.method_array
%w[method1 method2]
end

def a_few_methods
self.class.method_array.each { |s| send s }
end
end


I see that Method inherits Object, but I don't see any way to get 'under the hood' and grab things from it, aside from reading the source file into a string. Is there another way?

Answer

Did you try something like this?

def self.method_array
    arr = [method(:method1), method(:method2)
end

And then I would call it like

self.class.method_array.each { |s| s.call }

I created a program that looks like this:

def test_one
    puts "test one"
end

def test_two
    puts "test two"
end


def few_methods
    arr = [method(:test_one), method(:test_two)]
end


a = few_methods
a.each {|i| i.call  }

And when I run it I get the text printed out line by line. Don't know if this is something that might help you.

Comments