0

I have a table of scores that need processing at certain points. I am trying to avoid having walls of repetitive code so I am trying to get the values dynamically just by sending in the metric value but I cannot seem to get the syntax right and wasn't even sure how to properly search for this.

A typical value I need is something like this

s = score.total_weighted_strategic_values_score

All of these have the same structure to the name but one part changes based on the metric, so I have been trying something like this

s = score.total_weighted_"#{metric}"_score

Where metric is equal to a string strategic_values or whatever the metric is named.

This throws a syntax error, however, and I cannot find anything else to try. any help would be greatly appreciated, thanks!

Rockwell Rice
  • 3,376
  • 5
  • 33
  • 61
  • 2
    This has been probably answered before, but try with `send` or `public_send` (depending on the method) `score.send("total_weighted_#{metric}_score")`. – Sebastián Palma Nov 14 '19 at 16:57

1 Answers1

3

You need to use public_send:

s = score.public_send("total_weighted_#{metric}_score")

Some more reading on it: http://vaidehijoshi.github.io/blog/2015/05/05/metaprogramming-dynamic-methods-using-public-send/

Mark
  • 6,112
  • 4
  • 21
  • 46