Home > Software design >  Append the count to a variable name in ruby
Append the count to a variable name in ruby

Time:10-27

I have the following code:

count = 0
3.times do |survey|
  count = count   1
  @psychological_safety_score_   count.to_s  = Team.get_psychological_safety_score(@team, count)
end

This gives me the error undefined method to_s= for 1:Integer

I'm also tried @psychological_safety_score_ #{count.to_S} with no luck.

The end goal is to get instance variables of psychological_safety_score_1...3

CodePudding user response:

The Ruby language itself does not allow you to compute variable names by interpolating data into them.

It is still possible to do what you want though, using instance_variable_set.

score = Team.get_psychological_safety_score(@team, count)
variable = :"@psychological_safety_score_#{count}"
instance_variable_set variable, score

Also, count is redundant. Integer#times iterates self times, yielding the current index to the block. It can be used as the count.

  •  Tags:  
  • ruby
  • Related