I am trying to create a Ruby class where the initialize
method takes a hash of options. I then have those options as attr_accessor
s for the class. Now, I could do something like
class User
attr_accessor :name, :email, :phone
def initialize(options)
self.name = options[:name]
self.email = options[:email]
self.phone = options[:phone]
end
end
User.new(:name => 'Some Name', :email => 'some-name@some-company.com', :phone => 435543093)
but it doesn't feel very DRY to me. Instead, I would like to do
class User
attr_accessor :name, :email, :phone
def initialize(options)
options.each do |option_name, option_value|
# Does not work!!
self.send(option_name, '=', option_value)
# Does not work either!!
self.send(option_name, '=' + option_value)
en开发者_如何学运维d
end
end
User.new(:name => 'Some Name', :email => 'some-name@some-company.com', :phone => 435543093)
but I cannot get the syntax to work!
What am I doing wrong?
You're getting this problem because the method name is wrong. When using a send with a setter, you'll need to include the =
in the method name, like this:
self.send("#{option_name}=", option_value)
The above should do the trick.
精彩评论