在ruby中将字符串转换为变量名
发布时间:2020-12-17 03:12:27 所属栏目:百科 来源:网络整理
导读:我有变数 % mon_has_two_sets_of_working_hours = 0 % % tue_has_two_sets_of_working_hours = 0 % % wed_has_two_sets_of_working_hours = 0 % 我想动态更改这些变量的值. % days_array = ['mon','tue','wed'] % % days_array.each do |day| % % if conditi
我有变数
<% mon_has_two_sets_of_working_hours = 0 %> <% tue_has_two_sets_of_working_hours = 0 %> <% wed_has_two_sets_of_working_hours = 0 %> 我想动态更改这些变量的值. <% 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 该值未分配.有没有办法动态地为变量赋值? 解决方法
我认为没有办法做到这一点.有实例或类变量,但对于局部变量,很少需要.
在你的情况下,你真的应该有哈希数据.此外,像这样的逻辑真的不属于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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |