thebenman
thebenman

Reputation: 1621

How to call a method with question mark via send in ruby

I have methods generated for a list of symbols. One of the methods includes a question mark in its definition. I want to invoke such a method with a variable holding that symbol.

Suppose we generate a method for :check_element symbol and the corresponding method signature would look like.

class A
    def check_element?

    end
end

Now I have a variable flag = :check_element and I'm unable to call the method like A.send(flag)

but A.send((flag.to_s + '?').to_sym) works.

I'm thinking if there is a better way to achieve this.

Upvotes: 0

Views: 333

Answers (1)

spickermann
spickermann

Reputation: 106932

There is no need to translate the method name argument to a symbol because send accepts a string too. That allows simplifying your example to

A.send(flag.to_s + '?')

Which can be simplified using string interpolation to

A.send("#{flag}?")

Upvotes: 2

Related Questions