使用类实例将值从一个列表分配给另一个列表

时间:2014-03-14 23:54:39

标签: ruby

我完全不知道如何解决这个问题。我想在

时将一个列表属性分配给另一个列表属性
class System
# can access from outside of class
attr_reader :id, :os, :basebox

    def initialize(id, os, basebox, vulns=[], networks=[])
    @id = id
    @os = os
    @basebox = basebox

    @data = {
     "vulns" => vulns,
     "networks" => networks  
    }
end
 end

class Basebox
attr_accessor :name, :os, :distro, :vagrantbase, :url
end


p base
p system

剪切输出

#<Basebox:0x007fbc4b12a7c8 @name="precise",  @vagrantbase="precise32">

#<System:0x007fbc4b12bb00 @id="system3", @os="linux", @basebox="test">

如果我这样做

p base.vagrantbase
p system.basebox

输出

"CentOS6.2withpuppet"
"test"

我期待。

我想将@vagrantbase值分配给@basebox值,但是当我这样做时

system.basebox = base.vagrantbase

我收到未定义的方法`basebox =&#39;

1 个答案:

答案 0 :(得分:1)

System中,attr_reader :id, :os, :basebox不会为您创建setter方法#basebox=。你需要写如下:

attr_reader :id, :os # if you don't want to have #id= and #os=
attr_accessor :basebox # but you want both #basebox= and #basebox

阅读此#attr_readerattr_accessor方法。