在 Ruby 中,我可以在 initialize 方法中以某种方式自动填充实例变量吗? [英] in Ruby can I automatically populate instance variables somehow in the initialize method?

查看:24
本文介绍了在 Ruby 中,我可以在 initialize 方法中以某种方式自动填充实例变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中,我可以在 initialize 方法中以某种方式自动填充实例变量吗?

in Ruby can I automatically populate instance variables somehow in the initialize method?

例如,如果我有:

class Weekend
  attr_accessor :start_date, :end_date, :title, :description, :location

  def initialize(params)
    # SOMETHING HERE TO AUTO POPULATE INSTANCE VARIABLES WITH APPROPRIATE PARAMS
  end

end

推荐答案

您可以使用 instance_variable_set 像这样:

You can use instance_variable_set like this:

params.each do |key, value|
  self.instance_variable_set("@#{key}".to_sym, value)
end

这篇关于在 Ruby 中,我可以在 initialize 方法中以某种方式自动填充实例变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆