How to modify Hash to enable access of element 'hash[:a][:b]' by shorter 'hash[:a,:b]' in Ruby?
Date : March 29 2020, 07:55 AM
it helps some times I would be happy to access any element of multi-dimensional hash-array by a shorter expression , I have fixed my code, so now it works class AutoHash < Hash
def initialize *args
super
@update, @update_index = args[0][:update], args[0][:update_key] unless
args.empty?
end
def [] key,*args
if args.count > 0
self[key][*args]
else
if self.has_key? key
super key
else
AutoHash.new :update => self, :update_key => key
end
end
end
def []= *args
v = args.pop
k = args.shift
if args.count > 0
self[k][*args]= v
else
@update[@update_index] = self if @update and @update_index
super k,v
end
end
end
a = AutoHash.new
a[:a][:b][:c] = 123
a[:a,:b,:c] = 321
p a # => {:a=>{:b=>{:c=>321}}}
h[:a][:b][:c] = 123
p h.path(:a,:b,:c) # => 123
h.path(:a,:b,:c)= 321
p h #=> {:a=>{:b=>{:c=>321}}}
mypath = [:a,:b,:c]
p h.path(mypath) #=> 321
|
Inserting values into a Hash for YAML dump
Date : March 29 2020, 07:55 AM
Hope that helps I'm creating a hash that will eventually be dumped on disk in YAML, but I need to capture multiple values stored in a file on disk and insert them into a hash. I can successfully create a variable with comma separated values, but I need to insert those values into a my "classes" key: , You'd probably want something like: test_hash = {'Classes' => variable_values.split(',')}
|
Ruby: How to populate subclass of Hash from Hash
Tag : ruby , By : cameron
Date : March 29 2020, 07:55 AM
Any of those help The cleanest, in my experience, is to leave the initializer alone and to rely the class' [] operator: >> class SubHash < Hash; end
=> nil
>> a = Hash[{:a => :b}]
=> {:a=>:b}
>> a.class
=> Hash
>> b = SubHash[{:a => :b}]
=> {:a=>:b}
>> b.class
=> SubHash
|
For a hash of objects in ruby, hash.keys.index(obj) works but hash.has_key?(obj) does not. Why?
Date : March 29 2020, 07:55 AM
hope this fix your issue First, this drove me nuts. What you're doing looked absolutely correct to me, and, as you already know, doesn't work. I can take you part of the way to a solution: def hash
1
end
|
dump hash values to yaml file sequentially in perl
Tag : perl , By : user179863
Date : March 29 2020, 07:55 AM
|