I am trying to implement a class that takes a hash as a constructor as part of my Ruby learning.
This is what I have so far:
class Example
attr_accessor :bar, :baz, :some
def initialize args
args.each do |k,v|
instance_variable_set("@#{k}", v) unless v.nil?
end
end
my_hash = Example.new(foo: {bar: "x", "baz" => "y"}, "some" => "other")
end
The above is supposed to read the values as follows:
my_hash.foo.bar
=> "x"
my_hash.foo.baz
=> "y"
my_hash.some
=> "other"
my_hash.foo.class
=> Example
my_hash.unknown
=> nil
and also override the values and assign new ones. However, after I implemented this apparently, this code snippet here:
def initialize args
args.each do |k,v|
instance_variable_set("@#{k}", v) unless v.nil?
end
end
is no good because it does not allow assigning of params? Not sure what that means.
This is one of the tests I am not passing
it 'should store my_hash from hash passed through constructor' do
my_hash = Example.new({p1: 'test', 'p2' => {'p3' => [10, 12]}, p4: {}})
expect(my_hash.p1).to eq('test')
expect(my_hash.p2.p3).to eq([10, 12])
expect(my_hash.p2).to be_a(Example)
end
And the test that is failing my initialize method is this one:
it 'should allow assigning config params' do
my_hash = Example.new
my_hash.some = 'test'
my_hash.other = 'test2'
my_hash.yet_one_more = {}
my_hash.yet_one_more.test = 'test'
expect(my_hash.some).to eq('test')
expect(my_hash.other).to eq('test2')
expect(my_hash.yet_one_more.test).to eq('test')
end