I am quite new to Ruby, I am using HashWithIndifferentAccess for hash feature in Ruby. So my code is like:
def someFunction
array_list = []
some_array.each do | x |
new_hash = HashWithIndifferentAccess.new
// add entries to new_hash
array_list.push(new_hash)
end
array_list
end
Problem is: for each iteration I am initializing new hash, But if i do following, entry in array_list becomes empty:
def someFunction
array_list = []
new_hash = HashWithIndifferentAccess.new
some_array.each do | x |
// add entries to new_hash
array_list.push(new_hash)
new_hash.clear
end
array_list
end
I don't want to initialize new hash for each iteration, Any solution for this issue ?
I don't want to initialize new hash for each iteration
Why not? What is the reasoning behind this? You have to, otherwise it cannot work.
If you don't create a new hash each iteration, you're pushing the same hash into the array every time. Each element in the array is the same object , sharing the same state. There is only one hash , when you clear it, all the references to that same hash are obviously also cleared, because they are all the same object.
Any solution for this issue ?
Yes, you already have it: You need to create a new hash each iteration.
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.