I need to create the name of a dictionary using the name of the current iteration of an array.
For example:
sites = ["google", "facebook", "twitter", "stackoverflow"]
sites.each do |site|
#{site}_success_hash = {} <-- I need the correct syntax for achieving this result.
... populate ... hash
end
So I would want 4 hashes named google_success_hash
, etc.
I can't figure this out and it's driving me insane.
Have you considered to just nesting the hashes instead of keeping them in separate variables?
Something like this:
success_hash = {}
sites.each do |site|
success_hash[site] = #populate hash
end
The thing you asked for could however be accomplished like this (assuming it's ok to use instance variables):
instance_variable_set("@#{variable_name}", :something)
(see the answer here )
First of all use symbols instead of strings for your sites:
sites = [:google, :facebook, :twitter, :stackoverflow]
Then I think this might work:
sites.each do |site|
instance_variable_set("@#{site}_success_hash", {})
# populate @site_success_hash
end
Notice that you're setting an instance variable here.
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.