Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在ruby中将字符串转换为变量名_Ruby - Fatal编程技术网

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

在ruby中将字符串转换为变量名,ruby,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 %> 我想动态更改这些变量的值 <% days_array = ['mon', 'tue', 'wed'] %> <% days_array.each do |

我有变量

 <% 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

#我想在这里设置%>
结束
结束

未指定该值。有什么方法可以动态地给变量赋值吗?

我不认为有什么方法可以做到这一点。对于实例变量或类变量,没有什么好的需求,但是对于局部变量,很少有好的需求

在您的情况下,您真的应该将数据放在散列中。此外,这种逻辑在雇员再培训局是不适用的。你想要的是:

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

现在,我知道这个问题有点老了,但是有一个更简单的方法可以做到这一点,就是使用标准的Ruby
send
方法。这实际上是使Ruby在元编程世界中变得如此敏捷的方法之一

这实际上是我在Rails应用程序中使用的配置设置:

# In a YAML    
twitter:
  consumer_key: 'CONSUMER-KEY'
  consumer_secret: 'CONSUMER-SECRET'
  oauth_token: 'OAUTH-KEY'
  oauth_token_secret: 'OAUTH-SECRET'

...

# And in your file.rb
config = YAML.load_file(Rails.root.join("config", "social_keys.yml"))[Rails.env]['twitter']

Twitter.configure do |twitter|
  config.each_key do |k|
    twitter.send("#{k}=", config[k])
  end
end

它很干燥,很容易理解。:)

这个老问题的另一个答案

在我的场景中,我想计算一天中有多少次出现在天数数组中(
day\u array
)。我不需要知道一天是否没有出现在
day\u数组中,因此我没有像在中那样初始化
days\u计数

我是这样做的:

def count_days(day_array)
  days_count = {}
  day_array.each do |day|
    days_count[day].nil? ? days_count[day] = 1 : days_count[day] = days_count[day] + 1
  end
  puts days_count
end
如果我在irb中复制并粘贴上述内容,则:

> count_days(%w[SU MO])
{"SU"=>1, "MO"=>1}

> count_days(%w[SU SU MO])
{"SU"=>2, "MO"=>1}

基本上,与先前的答案一致。但是,我认为再举一个例子也无妨。

Do,Do,Do使用数组(或散列)。答案应该有帮助,它建议
instance\u variable\u set
。动态创建变量名在某些语言中是可行的,包括Ruby,但多年来一直不受欢迎,而且被认为是一种好奇心。它会导致混乱,从而导致维护问题,因此请避开该问题并使用散列。如果变量名来自用户提供的输入,也可能导致安全问题,或者如果名称与以前创建的变量冲突,则可能导致奇怪的错误。使用eval是可行的,但您说不应该这样做是对的。使用散列是更好的解决方案。或者您可以将此块传递给
inject
{| hash,day | hash.merge(day=>0)}