简体   繁体   中英

Ruby each loop x to variable substitution

<% @parts.each do|x| %>


<% @bbb = Relation.where(part: "#{x}") %>
<%= **@"#{x}"** = @bbb.collect {|x| x.car} %>

<% end %>

I'm trying to set the variable in line 3 to the x part value @"#{x}". I can't find the right syntax. I know about send(x) and x.to_sym. But I need to know how to set x in the each loop to an @variable with @. Thanks!

So you're looking for instance_variable_set

instance_variable_set "@#{x}", @bbb.collect { |x| x.car }

But this is probably not the best way to handle this. Without seeing the code that uses it, its hard to really say, but maybe consider putting the results into a hash: result[x] = @bbb.collect { |x| x.car } result[x] = @bbb.collect { |x| x.car }

Also note that "#{x}" is the same as x.to_s

Also, it's best to avoid querying models directly in your views (assuming you're doing Rails here, since you appear to be using ActiveRecord), because it mixes presentation with code (you can't take them as separate pieces. It has a tendency to get really ugly), it couples your view to the one use case you initially had (can't present different data in the same view even though it should be presented the same). Consider moving this code into your controller (or even some other object whose responsibility is to manage the querying of this data, leaving your controller responsibilities at just dealing with the request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM