So I am working on an application where I have an array where I need to the sum of the values of members of the array, if they fulfill certain conditions. It looks like this:
if !A and !B
array.each do {|a| if (some condition) sum += a }
if A and !B
array.each do {|a| if (some other condition) sum += a}
etc.
Now this can easily become much more complicated if there are more flags that can change what needs to be done inside the loop, i.e. which members of the array should be added to the sum and which shouldn’t. For each possible permutation you spawn a whole bunch of code that essentially does the same thing. I solved this problem by using the eval function.
The eval functions takes a string and evaluates it as code. So for instance, eval(“1 == 1″) would return true. You can use this to make an array of strings with stuff that needs to be done inside that loop. As an example consider this:
conditions = Array.new
if params[:some_id] != 0 : conditions << “self.some_id == params[:some_id]” end
You can add more conditions, depending on parameters passed to the function and then join them together:
conditions_string = conditions.join(‘ && ‘)
Then you only need to make one loop:
array.each do {|a| if eval (conditions_string) sum += a }
You could, of course, join the conditions array with || or include the logical operator in the string itself.
Popularity: 67% [?]