DRY Ruby Initialization with Hash Argument
Posted
by ktex
on Stack Overflow
See other posts from Stack Overflow
or by ktex
Published on 2010-04-21T05:23:37Z
Indexed on
2010/04/21
8:13 UTC
Read the original article
Hit count: 316
I find myself using hash arguments to constructors quite a bit, especially when writing DSLs for configuration or other bits of API that the end user will be exposed to. What I end up doing is something like the following:
class Example
PROPERTIES = [:name, :age]
PROPERTIES.each { |p| attr_reader p }
def initialize(args)
PROPERTIES.each do |p|
self.instance_variable_set "@#{p}", args[p] if not args[p].nil?
end
end
end
Is there no more idiomatic way to achieve this? The throw-away constant and the symbol to string conversion seem particularly egregious.
© Stack Overflow or respective owner