我是
Ruby的新手,我只是在玩想法,我想要做的是从我创建的country_array中删除@continent数据.完成了大量的搜索,可以找到有关完整删除元素的相关信息,但无法找到如何专门删除@continent数据.请保持任何答案相当简单,因为我是新的,但任何帮助非常感谢.
class World include Enumerable include Comparable attr_accessor :continent def <=> (sorted) @length = other.continent end def initialize(country,continent) @country = country @continent = continent end end a = World.new("Spain","Europe") b = World.new("India","Asia") c = World.new("Argentina","South America") d = World.new("Japan","Asia") country_array = [a,b,c,d] puts country_array.inspect [#<World:0x100169148 @continent="Europe",@country="Spain">,#<World:0x1001690d0 @continent="Asia",@country="India">,#<World:0x100169058 @continent="South America",@country="Argentina">,#<World:0x100168fe0 @continent="Asia",@country="Japan">]
解决方法
您可以使用remove_instance_variable.但是,由于它是一个私有方法,您需要重新打开您的类并添加一个新方法来执行此操作:
class World def remove_country remove_instance_variable(:@country) end end
然后你可以这样做:
country_array.each { |item| item.remove_country } # => [#<World:0x7f5e41e07d00 @country="Spain">,#<World:0x7f5e41e01450 @country="India">,#<World:0x7f5e41df5100 @country="Argentina">,#<World:0x7f5e41dedd10 @country="Japan">]