ActAsHash

I have no idea if someone hacked something like this already, i tried
searching with google but it’s hard to type good keys … anyway here’s
what i wrote for SOAP4R that had LOTS of instance variables that i
already had in hash and wanted eay way to assign them.

this should work for almost every class and should provide nice and easy
way to assigning values to instance variables in hash-like way.

of course it exposes all instance variables so encuspulaction (or
whatever you spell it) goes flying out of window.

module ActAsHash
def
self.instance_variable_get(("@"+index.to_s).to_sym)
end

def []=(index,value)
self.instance_variable_set(("@"+index.to_s).to_sym, value)
end

def from_hash(hash)
hash.each_pair do |k,v|
self[k]=v
end
end
end

and use it simply like

class A
include ActAsHash

attr_accessor :foo
end

a = A.new
a[“foo”] = :bar
a.foo => :bar
a[:foo] => :bar

i hope it’s usefull for someone :slight_smile: mayby it can find place in Facets :wink:

Marcin R. wrote:

self.instance_variable_get(("@"+index.to_s).to_sym)

ISTR that “@”+index.to_s is slower than “@#{index}”.

Also, you don’t need to call #to_sym. The string is enough.

Joel VanderWerf wrote:

Marcin R. wrote:

self.instance_variable_get(("@"+index.to_s).to_sym)

ISTR that “@”+index.to_s is slower than “@#{index}”.
i think concantation is faster then creating new one and i have no idea
what ISTR mean

Also, you don’t need to call #to_sym. The string is enough.

yep that’s true :slight_smile: i didn’t know that.

thanks for fixes

Marcin R. wrote:

Joel VanderWerf wrote:

Marcin R. wrote:

self.instance_variable_get(("@"+index.to_s).to_sym)

ISTR that “@”+index.to_s is slower than “@#{index}”.
i think concantation is faster then creating new one and i have no idea
what ISTR mean

Eh. It’s not as much as I remembered:

require ‘benchmark’

Benchmark.bmbm(12) do |bm|
n = 1_000_000
index = “foo”
@foo = 123

bm.report(’"@"+index.to_s’) do
n.times do
instance_variable_get("@"+index.to_s)
end
end

bm.report(’"@#{index}"’) do
n.times do
instance_variable_get("@#{index}")
end
end
end

END

Rehearsal --------------------------------------------------
“@”+index.to_s 1.170000 0.010000 1.180000 ( 1.178025)
“@#{index}” 0.960000 0.000000 0.960000 ( 0.954115)
----------------------------------------- total: 2.140000sec

                  user     system      total        real

“@”+index.to_s 1.170000 0.000000 1.170000 ( 1.174559)
“@#{index}” 0.940000 0.000000 0.940000 ( 0.945398)

ISTR that ISTR means I seem to recall, but I might be wrong :wink: