'How can I get only method name that return true

As I written in title, How can I get method name that return true.

def foo
 true 
end 

def bar 
 false
end 

def baz 
 false 
end 

arr = [foo, bar, baz]
# above return [true, false, false]
# My teribble way 
%w(foo bar baz).zip(arr).select{|a, b| b}
# => [["foo", true]]

I want to know that is method name. In the above case is foo. Any better idea?



Solution 1:[1]

I would use:

%w(foo bar baz).select { |name| send(name) }
#=> ["foo"]

Or even shorter:

%w(foo bar baz).select(&method(:send))
#=> ["foo"]

Solution 2:[2]

p %w(foo bar baz).filter_map { |method_name| method_name if send(method_name) }

Output

["foo"]

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 spickermann
Solution 2