Jerome
Jerome

Reputation: 6189

Ruby concatenation and interpolation to generically create instance variable

a method is intended to generically work with variable klass to create an instance variable from a string concatenation, then subsequently execute an operation (counter) on it

string = "@new_" + klass.to_s.downcase
string = string + 1

while the string is generated correctly @new_office the operation cannot be effected because an integer is being summed to a string. The instance variable is already initialised & has to be incremented, not reset.

Other attempts via interpolation also generated errors

syntax error, unexpected string literal, expecting `end'
      @new_"#{klass.to_s.downcase}" = @new_"#{klass.to_s.downcase}" + 1

unexpected '=', expecting `end'
      "@new_#{klass.to_s.downcase}" = "@new_#{klass.to_s.downcase}" + 1

`@' without identifiers is not allowed as an instance variable name
      @"new_#{klass.to_s.downcase}" = @"new_#{klass.to_s.downcase}"

How should can instance variable be constructed via concatenation + interpolation?

Upvotes: 0

Views: 147

Answers (1)

Sampat Badhe
Sampat Badhe

Reputation: 9075

you can use instance_variable_set and instance_variable_get to set and get dynamic instance variable

self.instance_variable_set("@new_#{klass.to_s.downcase}", instance_variable_get("@new_#{klass.to_s.downcase}") + 1)

Upvotes: 1

Related Questions