Hendrik Kleine Hendrik Kleine - 4 months ago 14
Ruby Question

Ruby: Convert String to Symbol during String Interpolation

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)?

Answer

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 ')
Comments