Convert string to variable name in ruby

I have variables

 <% mon_has_two_sets_of_working_hours = 0 %>
 <% tue_has_two_sets_of_working_hours = 0 %>
 <% wed_has_two_sets_of_working_hours = 0 %>

I want to dynamically change the values ​​of these variables.

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

No value is assigned. Is there a way to assign a value to a variable dynamically?

+5
source share
3 answers

I don’t think there is a way to do this. Exists with instance or class variables, but rarely happens with local variables.

In your case, you really should have the data in a hash. Also, logic like this really doesn't belong to erb. You want something like:

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
+3
source

, cuestion , Ruby. , 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

.:)

+2

.

, (day_array). , day_array, days_count gunn .

:

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}

, . , , .

0

All Articles