Interpolate variable name in ruby

Asked

Viewed 252 times

2

Hello, I am developing a test automation where I have a variable that receives dynamic values, according to the test run.

In the case of the contents of each element changes according to the websites accessed. For example:

element :formulario, '#resultado'
element :formulario_a, '#resultado-a'
element :formulario_b, '#resultado-b'

I created a marry, where I try to interpolate the variable name, to reduce the written cost of when's in the code.

case valor
when 'a' || 'b'
  formulario_"#{valor}".click login
else
  formulario.click login
end

When executing the code I get the following error:

Nomethoderror: Undefined method click' for "formulario_a":String from (pry):3:inform'

How do I dynamize the name of the variable?

2 answers

1

Welcome.

There are several possibilities for you to do this, the one that is closest to what you are wanting to do is using the method send. I took the liberty of modifying your code a little to demonstrate its workings.

def formulario(login)
  puts "FORMULARIO"
end

def formulario_a(login)
  puts "FORMULARIO_A"
end

def formulario_b(login)
  puts "FORMULARIO_B "
end

def do_it(valor, login)
  if ['a', 'b'].include?(valor)
    send("formulario_#{valor}", login)
  else
    formulario(login)
  end
end

login = true
do_it('a', login)

do_it('b', login)

do_it('c', login)

The result of this code is.

FORMULARIO_A 
FORMULARIO_B
FORMULARIO

I hope it helped.

-1


You must take the reference for the variable using "val"

Something that looks like this:

var_suffix = valor ? "_#{valor}" || ''
form = eval("formulario#{var_suffix}")
form.set login if form

If you don’t want to use Eval, you can alternatively use the "Binding.local_variable_get"

var_suffix = valor ? "_#{valor}" || ''
form = binding.local_variable_get("formulario#{var_suffix}")
form.set login if form

Binding is a special object that allows you to access the local execution context. More details: http://ruby-doc.org/core-2.2.2/Binding.html

  • Thanks, solved through the first block of code. var_suffix = marca ? "_#{marca}" : '' form = eval("formulario#{var_suffix}") form.click

  • 1

    I don’t recommend using Eval. The best way to do this in Ruby would be with send, or something similar, anyway. = ) https://stackoverflow.com/questions/1902744/when-is-eval-in-ruby-justified

  • I agree that Eval has to be used carefully. In the case presented, there is no problem at all. I wouldn’t use Eval in most situations either, but local_variable_get. So I put it as an alternative.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.