darkwizdom
darkwizdom

Reputation: 23

How do I call a custom method for an object?

I have a class with several methods:

class Test
  def initialize (age, height)
    @age = age
    @height = height
  end

  def older
    @age = @age + 2
  end

  def shorter
    @height = @height - 5
  end
end

man = Test.new(40, 170)
man.older
man.shorter

[...]

I want to pass onto object man a custom method, that is, I want to write something like man.variablemethod and set .variablemethod to either .older or .shorter, depending on some other factors. How can I do that?

I figured out that I can call "if condition then man.older", but I do not want to use if, especially when I have twenty different methods to choose from.

Upvotes: 2

Views: 70

Answers (1)

Brandan
Brandan

Reputation: 14983

Sounds like you need send:

man.send(method_name)

You can pass a string or symbol representing the name of the method you wish to call, even pass additional arguments too:

def man.older_by_increment(years)
  @age += years
end

man.send(:older_by_increment, 7)

This also allows you to call private and protected methods from anywhere:

class Man

  # ...

  private

  def weight
    @weight
  end
end

Man.new.weight         # => private method `weight' called for #<Man:0x10bc956d8> (NoMethodError)
Man.new.send(:weight)  # => @weight

Upvotes: 3

Related Questions