开发者

self.send(method, =, value) does not work

开发者 https://www.devze.com 2023-02-03 11:30 出处:网络
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

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)
    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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号