Ruby - How to use a method parameter as a variable name?

How to use a parameter value as a variable name of an instance of an object?

This is an object.

Class MyClass    
    def initialize(ex,ey)
      @myvar = ex
      @myothervar = ey
    end
end

I have the following method

def test(element)
  instanceofMyClass.element  #this obviously doesnt work
end

How can I get a test method that returns the value myvar or myothervar depending on the element parameter. I do not want to write an if condition, although I want to pass myvar or myother var through an element to an object instance, if possible.

+3
source share
3 answers
def test(element)
  instanceofMyClass.send(element.to_sym)  
end

You will get a missing method error if instanceofMyClass does not respond to the element.

+4
source
def test(element)
  instanceofmyclass.instance_variable_get element
end

test :@myvar # => ex
test :@myothervar # => ey
+3
source

send(), , . - , , , . , .

require 'forwardable'
class A
  extend Forwardable
  def_delegators :@myinstance, :foo, :bar

  class B
    def foo
      puts 'foo called'
    end

    def bar
      puts 'bar called'
    end

    def quux
      puts 'quux called'
    end

    def bif
      puts 'bif called'
    end
  end

  def initialize
    @myinstance = B.new
  end

  %i(quux bif).each do |meth| # note that only A#quux and A#bif are defined dynamically
    define_method meth do |*args_but_we_do_not_have_any|
      @myinstance.send(meth)
    end
  end
end

a = A.new

a.foo
a.bar

a.quux
a.bif
0

Source: https://habr.com/ru/post/1734312/


All Articles