【问题标题】:Convert instance variables and their values into a hash将实例变量及其值转换为哈希
【发布时间】:2015-05-08 22:31:08
【问题描述】:

我有一个类 MyClass 与实例变量 @id@color

class MyClass
  attr_accessor :id, :color
end

我通过以下方式创建了一个对象:

d = MyClass.new
d.id = 2
d.color = 'red'
d #=> #<MyClass:0x00000005fb52c0 @id=2, @color="red"> 

我想得到一个包含实例变量及其值的散列:

d.to_hash #=> { id: 2, color: 'red'}

实现这种方法的最佳方法是什么?

【问题讨论】:

  • 显示d[1]这个表达式有什么意义?
  • 向你展示我在控制台中得到的这个输出... => #<0x00000005fb52c0>

标签: ruby hash instance-variables


【解决方案1】:
class Klass
  def initialize
    @a = 2
    @b = 2
  end

  # define your own methods
  def attributes
    instance_variables.map do |var| 
      [var[1..-1].to_sym, instance_variable_get(var)]
    end.to_h
  end
end

Klass.new.attributes # => {:a=>2, :b=>2}

【讨论】:

  • 编写自己的方法很酷,但我希望 ruby​​ 有现成的方法:)
  • @Ann Ruby 把它作为练习留给我们.. :p
  • @Ann 如果你打算使用 Rails,有一个 attributes 方法
【解决方案2】:

Struct 是一种构建类的方法,其中内置了一些额外的:一种简单的初始化方法和一个to_h 方法。

MyClass = Struct.new(:id, :color)
d = MyClass.new(2, "red")
p d.to_h # => {:id=>2, :color=>"red"}

# MyClass is a Class:
p d.class # => MyClass

【讨论】:

    猜你喜欢
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 2019-05-23
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    相关资源
    最近更新 更多