self.send (método, =, valor) no funciona

I am trying to create a Ruby class where the initialize method takes a hash of options. I then have those options as attr_accessors 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)
    end
  end
end

User.new(:name => 'Some Name', :email => 'some-name@some-company.com', :phone => 435543093)

but I cannot get the syntax to work!

¿Qué estoy haciendo mal?

preguntado el 09 de enero de 11 a las 02:01

1 Respuestas

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.

Respondido el 09 de enero de 11 a las 05:01

Thank you!! That makes sense. - raikiri

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.