我循环遍历一段代码,每次都将变量" filter_index",从1增加到2,再到3 ......等等。
我想使用此变量来访问不同的符号:
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
这导致
AND @ filter1_field_name AND @ filter2_field_name AND @ filter3_field_name GROUP BY
但是期望的结果是
AND地区和国家和城市GROUP BY
我想知道为什么 filter_field_name.to_sym 无效(或者说,我做错了什么)?
答案 0 :(得分:1)
您可以使用instance_variable_get
函数获取变量值。
替换
行filter_field_name = "@filter#{filter_index.to_s}_field_name"
与
filter_field_name = instance_variable_get("@filter#{filter_index.to_s}_field_name")
编辑:
我认为您可以将字段名称放入数组中,并使用join
方法将值连接起来。
fields = ['Region','Country','City']
fields.join(' AND ')
答案 1 :(得分:0)
您可以使用instance_variable_get
或eval
filter_field_name = instance_variable_get("@filter#{filter_index.to_s}_field_name")
或
filter_field_name = eval("@filter#{filter_index.to_s}_field_name")