0

I am looping over a block of code, each time increasing variable "filter_index", from 1, to 2, to 3... etc.

I'd like to use this variable to access the different symbols:

filter1_field_name, filter2_field_name, filter3_field_name

@filter1_field_name = "Region"
@filter2_field_name = "Country"
@filter3_field_name = "City"

SELECT_STATEMENT = "GROUP BY "

numberOfFilters = 3

filter_index = 1
numberOfFilters.times do #Number of iterations 
    filter_field_name = "@filter#{filter_index.to_s}_field_name"
    SELECT_STATEMENT.sub! "GROUP BY", "AND #{filter_field_name.to_sym} GROUP BY"
  filter_index += 1
end

puts SELECT_STATEMENT

This results in

AND @filter1_field_name AND @filter2_field_name AND @filter3_field_name GROUP BY

But the desired result is

AND Region AND Country AND City GROUP BY

I'm wondering why filter_field_name.to_sym is not working (or rather, what I'm doing wrong)?

3
  • The provided answers will do what you want. However, I suggest you consider storing the filters in an array, where item 0 of the array would be the first filter, item 1 would be the 2nd filter and so on. Commented Jul 29, 2016 at 13:44
  • .to_s can be removed as interpolation (#{}) is already doing that implicitly. Commented Jul 29, 2016 at 13:44
  • @BrunoFacca - that makes sense indeed. Cheers Commented Jul 29, 2016 at 13:46

2 Answers 2

1

You can use instance_variable_get function to get variable value.

Replace the line

filter_field_name = "@filter#{filter_index.to_s}_field_name"

with

filter_field_name = instance_variable_get("@filter#{filter_index.to_s}_field_name")

EDIT:

I think you can put the field names into an array and concat the values with join method.

fields = ['Region','Country','City']
fields.join(' AND ')
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, perfect. Learned something else!
.to_s is unnecessary.
0

you can use instance_variable_get or eval

filter_field_name = instance_variable_get("@filter#{filter_index.to_s}_field_name")

or

filter_field_name = eval("@filter#{filter_index.to_s}_field_name")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.