声明遍历哈希的实例变量! [英] Declaring instance variables iterating over a hash!

查看:142
本文介绍了声明遍历哈希的实例变量!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要执行以下操作:

我想声明一个迭代在字典上的类的实例变量。

I want to declare the instance variables of a class iterating over a dictionary.

让我们假设我有这个散列

Let's assume that i have this hash

hash = {"key1" => "value1","key2" => "value2","key3" => "value3"}

并且我想让每个键作为类的实例变量。我想知道我是否可以声明的变量迭代该哈希。类似这样的:

and i want to have each key as instance variable of a class. I want to know if i could declare the variables iterating over that hash. Something like this:

class MyClass
  def initialize()
    hash = {"key1" => "value1","key2" => "value2","key3" => "value3"}
    hash.each do |k,v|
      @k = v
    end
  end
end

我知道这不行!我只是把这段代码看看你能理解我想要更清楚。

I know this doesn't work! I only put this piece of code to see if you could understand what i want more clearly.

谢谢!

推荐答案

class MyClass
  def initialize()
    hash = {"key1" => "value1","key2" => "value2","key3" => "value3"}
    hash.each do |k,v|
      instance_variable_set("@#{k}",v)
      # if you want accessors:
      eigenclass = class<<self; self; end
      eigenclass.class_eval do
        attr_accessor k
      end
    end
  end
end

特征类是一个只属于单个对象的特殊类,因此定义的方法将是该对象的实例方法,但不属于该对象的普通类的其他实例。

The eigenclass is a special class belonging just to a single object, so methods defined there will be instance methods of that object but not belong to other instances of the object's normal class.

这篇关于声明遍历哈希的实例变量!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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