在ruby中将字符串转换为变量名

sri*_*ani 5 ruby

我有变数

 <% mon_has_two_sets_of_working_hours = 0 %>
 <% tue_has_two_sets_of_working_hours = 0 %>
 <% wed_has_two_sets_of_working_hours = 0 %>
Run Code Online (Sandbox Code Playgroud)

我想动态更改这些变量的值.

 <% days_array = ['mon', 'tue', 'wed'] %>

 <% days_array.each do |day| %>
   <% if condition? %>
    # here i want to set %>
     <% "#{day}__has_two_sets_of_working_hours" = 1 %>
  end
 end
Run Code Online (Sandbox Code Playgroud)

该值未分配.有没有办法动态地为变量赋值?

gun*_*unn 4

我认为没有办法做到这一点。有实例或类变量,但很少有必要使用局部变量。

在你的情况下,你确实应该将数据放在哈希中。而且,这样的逻辑确实不属于erb。你想要这样的东西:

working_hour_sets = %w[mon tue wed thu fri sat sun].inject({}) do |hash, day|
  hash[day]=0;
  hash
end
# puts working_hour_sets #=> {"wed"=>0, "sun"=>0, "thu"=>0, "mon"=>0, "tue"=>0, "sat"=>0, "fri"=>0}

working_hour_sets.each do |day, value|
  working_hour_sets[day] = 1 if condition?
end
Run Code Online (Sandbox Code Playgroud)