Home > Net >  How can I get only method name that return true
How can I get only method name that return true

Time:03-03

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?

CodePudding user response:

I would use:

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

Or even shorter:

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

CodePudding user response:

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

Output

["foo"]
  •  Tags:  
  • ruby
  • Related